You probably shouldn't do it this way. Depending on what you are actually trying to accomplish there are likely other options:
If you are just trying to have a dynamic option to select your search string you could do something like this instead:
#!/bin/bash
pattern=$1
ls -alt | grep "${pattern:-.}"
This will search for whatever your first positional parameter is, or anything if none is provided.
Or if you're trying to act on some condition:
#!/bin/bash
cmd=(ls -alt)
p1=usersfile
p2=usersfolder
if [[ condition1 ]]; then
p=$p1
elif [[ condition2 ]]; then
p=$p2
fi
"${cmd[@]}" | grep "$p"
Or in a function:
#!/bin/bash
ls_func () {
local p=$1
ls -alt | grep "${p:-.}"
}
while getopts p:c: opt; do
case $opt in
c) command=$OPTARG;;
p) pattern=$OPTARG;;
esac
done
if [[ $command == 'ls' ]]; then
ls_func "$pattern"
fi
a. '{ etc. }'
andb. '{ etc. }'
. Do you want to assign the "joint command" to a variablea
andb
respectively which you then want to "execute"?ls -lt
output for something containing the stringuserfolder
and/or the stringuserfile
. Could you rephrase your question to show what the underlying issue is. Grepping the output ofls
is very rarely the correct approach. For example, why would you need to store thels
command in a variable? Why not create a shell function instead?