Shell script won't run properly when re-assign

2019-08-15 08:40发布

问题:

This question already has an answer here:

  • Command not found error in Bash variable assignment 5 answers
  • Variable variable assignment error -“command not found” 1 answer
  • Why does a space in a variable assignment give an error in Bash? [duplicate] 3 answers

So I've got a shell script to do some lazy stuff for if the directory isn't changing for a user. It's below. Essentially, it should be an if statement that if the user enters "default" for the directory, it'll pull them to the default directory for the files. However, I'm getting a command not found on line 16, which is the reassignment statement.

The entire if statement below:

if [ $directory = "default" ];
then 
    echo Enter your ldap:
    read $ldap
    $directory = "/usr/local/home/google/${ldap}/Downloads"
fi

I've tried doing it without the dollar sign too...nothing. What's going on here? New to shell, couldn't find this question asked before either.

回答1:

This is how you should assign a value to a variable in shell:

directory="/usr/local/home/google/${ldap}/Downloads"
  • No dollar ($) sign.
  • No space around equal (=) sign.

Also, you should wrap your variables inside double quotes ("). This way, you avoid errors with undefined variables, arguments with spaces, etc.


That gives us:

if [ "$directory" = "default" ]
then
    echo "Enter your ldap:"
    read $ldap
    directory="/usr/local/home/google/${ldap}/Downloads"
fi


标签: linux shell