0

I am a newbie to writing shell scripts. Please help me in parameterizing a variable value in my shell script.

I am taking command-line arguments for database name, server, user, and password in the following way:

database_name=$1
server=$2
user=$3 
password=$4

I want to understand how I can pass these values to a variable called sqlcmd. I pass these values in the following way and then echo to see the value of sqlcmd variable:

sqlcmd=sqlcmd -S $server -U $user -P $password
echo $sqlcmd

after making the shell script executable using chmod a+x on ubuntu. I run the script and get the following error

line 37: -S: command not found. Line 37 in my shell script is a line on which sqlcmd variable is initialized

P.S I am using WSL on a remote windows machine. I am not sure if that should cause an error.

  • Is `sqlcmd` supposed to contain the command line, or the results of executing the command? – chepner Apr 27 '21 at 16:23
  • It is supposed to contain the command line. – shafia askari Apr 27 '21 at 16:25
  • What do you mean by "compile the shell script"? Typically, you execute shell scripts and do not compile them. – William Pursell Apr 27 '21 at 16:28
  • It might help to read https://stackoverflow.com/questions/2268104/command-not-found-error-in-bash-variable-assignment/2268117#2268117. When you omit the quotes, the line `sqlcmd=sqlcmd -S ...` attempts to run a command named `-S`. There is an explanation for that in the link. – William Pursell Apr 27 '21 at 16:30
  • @WilliamPursell that was a mistake and I have fixed it. – shafia askari Apr 27 '21 at 16:33
  • Does this answer your question? [How to store a command in a variable in a shell script?](https://stackoverflow.com/questions/5615717/how-to-store-a-command-in-a-variable-in-a-shell-script) – tripleee Apr 27 '21 at 16:43
  • Why are you not just executing the command? If the only reason you are storing it in a variable is to `echo` the value before you run it, there are better mechanisms to achieve that. (eg, `set -x` or `set -v`) – William Pursell Apr 27 '21 at 16:53

1 Answers1

0

You need quotes:

sqlcmd="sqlcmd -S $server -U $user -P $password"

Note that you may run into difficulties later trying to execute the contents of sqlcmd.

chepner
  • 497,756
  • 71
  • 530
  • 681
  • Yes. I want to execute later the contents of sqlcmd so I do not want to implement the variable value in quotes. – shafia askari Apr 27 '21 at 16:28
  • I think to execute it after you have defined as chepner has stated, you need to wrap the next part in backticks e.g. `\`$sqlcmd\`` – Disastron Apr 27 '21 at 16:41
  • 2
    @Cameron that's just a [useless echo](http://www.iki.fi/era/unix/award.html#echo) – tripleee Apr 27 '21 at 16:45
  • 1
    I'm not going to address that part of the question, aside from referring you [here](http://mywiki.wooledge.org/BashFAQ/050). – chepner Apr 27 '21 at 17:58