Ubuntu – Run a standard command in bash script

bashcommand linescripts

I am writing a bash script to automate several actions:

#!/bin/bash         

echo "Hello, World"
NAME="${1}"
PATH="${2}"
echo $NAME
echo $PATH
eval "ls"

I am going to call ls, ffmpeg and a lot of other commands.

However running my script gives me the following error:

/var/www/html# ./life.sh test midhand.mp4
+ ./life.sh test midhand.mp4
Hello, World
test
midhand.mp4
./life.sh: line 9: ls: command not found

How come? why not found? Maybe I should import a directory with scripts?

Best Answer

The variable PATH is a special shell variable. It defines the list of directories in which executables/commands can be found.

In the line PATH="${2}", you wipe out the default value of PATH and now the shell doesn't know where to find the ls command. For example, ls can be found in the directory /bin, but you modified PATH to have the value midhand.mp4 (the second argument), in particular PATH does not contain /bin and thus your shell cannot find the ls command.

Try this:

#!/bin/bash

echo "Hello, World"
the_name="${1}"
the_path="${2}"

echo "PATH is '$PATH'"
echo $the_name
echo $the_path
eval "ls"

Note. You can change the last line from eval "ls" to just ls.

You can run man bash to get further information.

Related Question