I have a script which takes input for two variables from users. Then, I try to use those variables in a command which is in turn being fed into a condition in an if. However, the user input value is not replacing my variables and as a result, my command is not working -

# Get acl and dc values
echo "Type the ACL name:"
read acl
echo "Type the DATACENTER name"
read dc
# see if sw-list-cisco file exists in ~/$acl directory"
if [ ` ls -1 ~/$acl/sw-list-cisco > /dev/null | wc -l ` -gt 0 ];
    echo "Going to do something"
     echo "no match !!!!!!!!!!!!!"

The if [ ` ls -1 ~/"$acl"/sw-list-cisco > /dev/null | wc -l ` -gt 0 ]; condition doesn't seem to be replacing $acl with the user input value. I have verified manually that sw-list-cisco exists in the ~/$acl directory. What am I missing?

  • If is not a loop (there is no iteration (repetition)) – ctrl-alt-delor May 13 '17 at 11:13

You rarely, if ever, need to parse the output from ls.

In this case, you may get by by just doing

if [ -f "$HOME/$acl/sw-list-cisco" ]; then

I'm using the -f test to test whether the given name exists and is the name of a regular file. I'm using $HOME rather than ~ since ~ does not behave as a variable inside quotes (and $HOME is much more descriptive, IMHO).

| improve this answer | |
if [ ` ls -1 ~/$acl/sw-list-cisco > /dev/null | wc -l ` -gt 0 ];

You redirect the output of ls to /dev/null, so nothing goes to wc, and it always prints 0. Same if you try it manually: ls / >/dev/null | wc -l vs. ls / | wc -l.

You probably wanted to redirect errors from ls to /dev/null instead:

if [ $(ls ~/"$acl/sw-list-cisco" 2>/dev/null | wc -l) -gt 0 ];

(-1 is not needed when the output goes to a pipe.)

But since it's just one file, [ -f ~/"$acl/sw-list-cisco" ] will do it more easily as @Kusalananda already answered. Even if you wanted a count of the files, it might be better to expand a glob to an array and count the elements.

| improve this answer | |
  • And anything which uses wc in a condition is probably useless. – tripleee May 13 '17 at 11:15
  • @tripleee, though ls doesn't have a switch for counting and I don't think find has one either – ilkkachu May 13 '17 at 11:21
  • Yeah, there's a corner case where you actually want to perform arithmetic on the actual number of matches; the real antipattern is comparing the count to nonzero when the shell already tells you whether something succeeded or not. – tripleee May 13 '17 at 11:28

Not the answer you're looking for? Browse other questions tagged or ask your own question.