简体   繁体   中英

shell script variable use

I'll get to the meat and bones:

MY_VAR=6
until [$MY_VAR = 0]
do
dir/dir_$MY_VAR.log
ps | grep "NAME_$MY_VAR.ksh"
check some things
if [results = ok]
echo "program $MY_VAR sucessful"
else
echo "program $MY_VAR failure"
MY_VAR = `expr $MY_VAR - 1`
done

Now I am getting the following errors MY_VAR not found and [6: not found, so I'm assuming a rather noobish mistake. I feel the logic is sound enough just a simple syntax error I am making somewhere by the looks of the two errors I think it could be in the declaration.

You need to have a space after [ and before ] since [ is actually a command and not a delimiter.

Here is your script re-written in Bash (or ksh):

my_var=6
until ((my_var == 0))
do
    dir/dir_$my_var.log    # I have no idea what this is supposed to be
    ps | grep "NAME_$my_var.ksh"
    # check some things
    if [[ $results = ok ]]
    then
        echo "program $my_var successful"
    else
        echo "program $my_var failure"
        ((my_var--))
    fi
done

However:

for my_var in {6..1}
do
    dir/dir_$my_var.log    # I have no idea what this is supposed to be
    ps | grep "NAME_$my_var.ksh"
    # check some things
    if [[ $results = ok ]]
    then
        echo "program $my_var successful"
    else
        echo "program $my_var failure"
    fi
done

Your two errors are caused by:

  • until [$MY_VAR = 0]
  • MY_VAR = $(expr $MY_VAR - 1)

[I've used $() instead of backticks because I couldn't get backticks into the code section]

The first problem is the lack of spaces around the square brackets - on both ends. The shell is looking for the command [6 (after expanding $MY_VAR ), instead of [ (have a look at /usr/bin/[ - it's actually a program). You should also use -eq to do numeric comparisons. = should work ok here, but leading zeros can break a string comparison where a numeric comparison would work:

until [ "$MY_VAR" -eq 0 ]

The second problem is you have spaces in your variable assignment. When you write MY_VAR = ... the shell is looking for the command MY_VAR . Instead write it as:

MY_VAR=`expr $MY_VAR - 1`

These answers directly answer your questions, but you should study Dennis Williamson's answer for better ways to do these things.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM