0

i'm stucked on this problem: i need a dynamic expression generation that has to be passed to ls command.

Here the code i tried:

op="ext"
fileName="MDL_test_"
fileExt=".csv"

if [[ $op == "noext" ]] ; then
    searchExp="*$fileName*"
else
    searchExp="*$fileName*$fileExt"
fi

ls "$("./files/"$searchExp)"

But when i execute the script this is what i get:

./ext_test.sh: line 15: ./files/MDL_test_30160410.csv.gz: Permission denied
ls: cannot access : No such file or directory

I think i'm doing something wrong, but i can't figure out it...

4
  • 1
    What are you actually trying to accomplish? You should not be using ls in scripts in the first place. Commented Nov 7, 2016 at 13:39
  • 1
    @tripleee Absolutely no issue with using ls in this case. Commented Nov 7, 2016 at 13:49
  • 1
    As a placeholder for a real command, it's fine; but then echo would work as well, and have fewer complicating side effects. Commented Nov 7, 2016 at 14:07
  • As a command it is fine.No idea why everyone seems to think using it bad. As long as you're not parsing the output there is nothing wrong with it at all. Echo would not work as well as it is a completely different command. ls formats the output completely differently from echo which may be desired, as well as lists directory contents, which echo will not. Commented Nov 7, 2016 at 14:27

1 Answer 1

3

You just need to build the string up in pieces; most of the syntax is evaluated by the shell before passing the expanded result to ls.

if [[ $op == noext ]]; then
  fileExt=
else
  fileExt=.csv
fi

ls ./files/*"$fileName"*"$fileExt"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.