Save parameter in variable with space

Consider the following output commands:

$ du -sm ~/Documents 
458 /home/utilisateur/Documents
$ du -sm ~/Documents --exclude='aa bb' --exclude='cc dd'
153 /home/utilisateur/Documents

I want to replace the exception with a single variable like this in order to get the same result.

$ du -sm ~/Documents "$c"

But, if I set a variable with the following, I failed. I tested:

$ c=--exclude='aa bb'\ --exclude='cc dd'
$ du -sm ~/Documents "$c"
458 /home/utilisateur/Documents

$ c="\"--exclude='aa bb' --exclude='cc dd'\""
$ du -sm ~/Documents $c
458 /home/utilisateur/Documents
du: cannot access '"--exclude='\''aa': No such file or directory
du: cannot access 'bb'\''': No such file or directory
du: cannot access 'dd'\''"': No such file or directory

$ c="--exclude='aa bb' --exclude='cc dd'"
$ du -sm ~/Documents "$c"
458 /home/utilisateur/Documents
$ du -sm ~/Documents $c
458 /home/utilisateur/Documents
du: cannot access 'bb'\''': No such file or directory
du: cannot access 'dd'\''': No such file or directory

Please help me fix my mistake. I know this about quotes.

+4
source share
2 answers
du --exclude='aa bb' --exclude='cc dd'

You have a few arguments, at least some of which contain spaces. It is not possible to put them in a single string variable in order to maintain separation between the arguments.

If you do

args="--exclude=aa bb --exclude=cc dd"
du $args

, du: --exclude=aa, bb, --exclude=cc dd.

,

du "$args"

args , du .

, , , du.

- :

args=("--exclude=aa bb" "--exclude=cc dd")   # initialize it
args+=("--exclude=ee ff")                    # you can even append to it
du -sm ~/Documents "${args[@]}"

. : script ? unix.SE

+2

script, :

du -sm "$path" "$exc"

exc

exc="--exclude=aa bb" 

- . , (, ):

OLDIFS="$IFS"
IFS="
"
# do your scripting stuff
# restore IFS
IFS="$OLDIFS"

EDIT: , --exclude.

+1

Source: https://habr.com/ru/post/1675167/


All Articles