help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] Quoting in variables to be used as command args


From: Geir Hauge
Subject: Re: [Help-bash] Quoting in variables to be used as command args
Date: Tue, 5 Jun 2012 19:54:04 +0200

2012/6/5 suvayu ali <address@hidden>:
> Hi Bash users/experts,
>
> I have a script that uses find to look for files in a source tree. I
> want to build the find command options conditionally, so I concatenate
> the options as needed to a variable and then finally run the find
> command with the variable as argument to get the file list.
>
>  [[ -n ${optargs[module]} ]] && \
>      findopts+=" -path *${optargs[module]}* "

Never mash multiple arguments into a single string. Use arrays or
functions. For this case, an array:

[[ $blah ]] && findopts+=( -name "*.$blah" )
#...
find . "address@hidden"

See http://mywiki.wooledge.org/BashFAQ/050


>  declare -a files
>  files=($(find "${srcdir}" -type f ${findopts} -iregex "${regex}"))

Don't fill an array using array=( $(command substitution) ), you get the
same problem with wordsplitting and pathname expansion as with your
findopts string. Use a while read loop instead.

files=()
while IFS= read -r -d '' file; do
    files+=("$file")
done < <(find "$srcdir" -type f \( "address@hidden" \) -print0)

Note that -print0 is a non-POSIX extension to find, but GNU and BSD find
has it.

See http://mywiki.wooledge.org/BashFAQ/020

-- 
Geir Hauge



reply via email to

[Prev in Thread] Current Thread [Next in Thread]