bash script variables
Hi there,
I have a very very simple bash script: #!/bin/bash mail=`/usr/bin/mail` echo "Hello there" | $mail -s "testing" twantrd exit 0 However, run trying to run it..it will give me "-s: command not found". If I replace $mail with just the command 'mail' it will work. Any ideas why? Also with ssh: #!/bin/bash ssh=`/usr/local/ssh` $ssh localhost It will give me this when trying to run: "./ssh_script: localhost: command not found" However, if I replace $ssh with just the command 'ssh' then it works. Why doesn't declaring these certain commands as variables work while commands such as 'date', 'hostname', etc.. work as variables? Hmmm... -twantrd |
Have you tried using normal quotes around /usr/bin/mail?
And execute the program. #!/bin/bash mail="/usr/bin/mail" echo "Hello there" | $($mail -s "testing" twantrd) exit 0 |
Ahhh thank you. DUH, that makes sense! Thanks!!
-twantrd |
Actually, I'm back again :). Ok so:
ssh="/usr/bin/ssh" works ssh=`/usr/bin/ssh` does not work But how come: hostname=`/usr/bin/hostname`works How come hostname works when you declare it as a variable and ssh doesn't?? Thanks! -twantrd |
I think this is whats happening:-
When you use Code:
hostname=`/usr/bin/hostname` Then when you call $hostname in a script it will be replaced with the hosts name, in my case desktop, which is the same as executing the program hostname. When you use Code:
ssh=`/usr/bin/ssh` Then when you call $ssh in a script it will be replaced with the output from ssh called with no parameters, Code:
usage: ssh [-1246AaCfghkNnqsTtVvXxY] [-b bind_address] [-c cipher_spec] You could test this by placing an Code:
echo $ssh |
Because hostname is a non interactive command that returns a string that is affected to the variable value, while ssh is an interactive command that returns nothing when launched without options or arguments. It should return its help message on stderr though, but this is not going to the variable. mail is also returning nothing on stdout, thus the initial script problem.
Single and double quotes are used to group strings, while back-quotes are executing the embedded string. Back quotes are becoming obsolete and should be replaced by the equivalent syntax: hostname=$(hostname) |
Ok, now I fully understand. Thanks to you both!!!
-twantrd |
It has nothing to do with the program being interactive or not.
var=`/usr/bin/program` or var=$(/usr/bin/program) means execute /usr/bin/program and store the output It's more or less like a pointer on char in C (char*), the value of which is computed by calling a function. var='/usr/bin/program' or var="/usr/bin/program" means store the string (value) "/usr/bin/program" into var. It's more or less like a pointer on a function in C (char*), though in this case it can perfectly be handled as a char*, as in: echo $var. Yves. |
All times are GMT -5. The time now is 06:53 AM. |