Looking at bash scripts sometimes I see a construction like this:
MYSQL=`which mysql`
$MYSQL -uroot -ppass -e "SELECT * FROM whatever"
Where in other scripts the command (mysql in this case) is used directly:
mysql -uroot -ppass -e "SELECT * FROM whatever"
So, why and when should which be used and for which commands – I've never seen echo used with which…
You can just do man which for details:
DESCRIPTION
which returns the pathnames of the files (or links) which would be executed in the current environment, had its arguments been given as commands in a strictly POSIX-conformant shell. It does this by search‐ ing the PATH for executable files matching the names of the arguments. It does not follow symbolic links.
So which mysql just returns current path of the mysql command.
However use of which in your examples just makes sure to ignore any alias set for mysql in your current environment.
However there is another clever shortcut to avoid which in shell. You can use call mysql with backslash:
\mysql -uroot -ppass -e "SELECT * FROM whatever"
This will be effectively same as what your 2 commands are doing.
From OP: The only reason to use which is to avoid possible problems with custom aliases (like alias mysql="mysql -upeter -ppaula"). And since it is pretty unlikely somebody would set an alias for say echo, we don't need this construction with echo. But it is very common to set an alias for mysql (nobody wants to memorize and type the 24 chars long password).
Largely they both are same:
Just which returns the absolute path of the binary. Sometimes special conditions when you are working with some third program executing the script or preparing the environment in which this script would run the entire path of the binary comes in handy.
Like in case of a scheduler. If you have scheduled one script then you will like to use the binary with its absolute path.
Hence:
mysql=`which mysql`
or
mysql=$(which mysql)
or even
/usr/bin/mysql <flags>
Your script from scheduler might have run using
mysql ....<flags>
but it wasn't a guarantee as explained in the previous post. Alias may be one of the reasons.
For the kind of problems not using the absolute path can bring, check this link
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With