Shubhi Agarwal
Shubhi Agarwal

Reputation: 21

Issue in shell script with replacing explicit string with a variable

I have been using a shell script which used to do something like this:

output=$(ls -R /logs/{abc,cde}/"$((${date}/100))"/*/out*${date}* | grep -v "Random" )
echo $output

On running this command, I used to get the files with either abc or cde at relevant location. You can ignore other variables like date etc

However, when I modified the script to take abc,cde as command line parameter instead of hardcoding in the script, it stopped working. I changed the command to:

output=$(ls -R /logs/{${list}}/"$((${date}/100))"/*/out*${date}* | grep -v "Random" )

where list is abc,cde

I tried a lot of different combinations of quotes etc but it does not seem to be working. Can someone help please with the correct syntax that it works properly

Upvotes: 1

Views: 201

Answers (2)

SLS
SLS

Reputation: 485

Try with this

  1. Assign abc and cde to an array ex - declare -a ARR=(abc cde)

  2. Assign it to variable like below.

    output=ls -R /logs/${ARR[@]/"$((${date}/100))"/*/out*${date}* | grep -v "Random"

Upvotes: 1

jeb
jeb

Reputation: 82307

It doesn't work, because the expansion order prevents it.

The order of expansions is: brace expansion; tilde expansion, parameter and variable expansion

You could solve it with using eval, but eval should be avoided at all.

Probably it's better to use find here.

find /logs -name 'abc/...' -o -name 'cde/...' 

This works even with variables

Or use the regex logic.

find /logs/ -regex '/logs/\(abc\|cde\).*'

Upvotes: 1

Related Questions