user3227783
user3227783

Reputation: 111

command works in terminal and not in script

The bellow commands works in terminal and prints value 1

count_XXX=`ll -d /usr/Systems/XXX* 2> /dev/null | grep ^d | wc -l`
echo "$count_XXX"

There is one directory and two softlinks in the directory /usr/Systems with the same name XXX*.

when i keep the same two lines in shell script. It prints value 0

This works fine in unix(both terminal and script) but when i try to run in linux server the issue happens(in script).

do i need to change something for Linux.

Thanks in advance.

Upvotes: 1

Views: 101

Answers (1)

anubhava
anubhava

Reputation: 785146

Using ll then grep and then wc is bit too much for counting directories and this is also error prone due to possibility of whitespace/newline in directory names.

In BASH use this simple snippet:

shopt -s nullglob
arr=( /usr/Systems/XXX*/ )
echo ${#arr[@]}
2
  • / at the end of your glob pattern makes sure it matches only directories.
  • shopt -s nullglob to make sure to not to print pattern when glob pattern doesn't match anything

Upvotes: 2

Related Questions