0

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 ];
then
    echo "Going to do something"
else
     echo "no match !!!!!!!!!!!!!"
fi

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?

2 Answers2

4

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).

Kusalananda
  • 333,661
1
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.

ilkkachu
  • 138,973
  • 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