Add command arguments using inline if-statement in bash

I would like to add an argument to a command in bash only if the variable is evaluated to a specific value. For example, this works:

test=1
if [ "${test}" == 1 ]; then
    ls -la -R
else
    ls -R   
fi

The problem with this approach is that I have to duplicate ls -Rboth when test, and in 1, or if it is something else. I would prefer if I could write this on one line, and not like that (pseudocode that doesn't work):

ls (if ${test} == 1 then -la) -R

I tried the following but it does not work:

test=1
ls `if [ $test -eq 1 ]; then -la; fi` -R

This gives me the following error:

./test.sh: line 3: -la: command not found
+4
source share
3 answers

More idiomatic version of svlasov answer :

ls $( (( test == 1 )) && printf %s '-la' ) -R

echo , printf %s, , .
, - , - . .

, , :

# Build up array of arguments...
args=()
(( test == 1 )) && args+=( '-la' )
args+=( '-R' )

# ... and pass it to `ls`.
ls "${args[@]}"

. OP , , ls -R -la "$PWD". : , , :

(( test == 1 )) && args+= ( '-la' "$PWD" ) # Add each argument as its own array element.

,

 ls `if [ $test -eq 1 ]; then -la; fi` -R

:

backticks ( , , $(...)) - - ( -), stdout.

, -la, . stdout, , , ​​ echo printf.

+11

echo:

test=1
ls `if [ $test -eq 1 ]; then echo "-la"; fi` -R
+3

, eval BASH :

myls() { local arr=(ls); [[ $1 -eq 1 ]] && arr+=(-la); arr+=(-R); "${arr[@]}"; }

:

myls
myls "$test"

script arr .

+2

All Articles