LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Calling alias command in script (https://www.linuxquestions.org/questions/linux-newbie-8/calling-alias-command-in-script-633350/)

snowman81 04-05-2008 09:54 PM

Calling alias command in script
 
I created an alias that is called "temp" and I am trying to call that in a script I wrote. I don't think it is in the path though. Does anyone know how I would go about either putting it in the path or calling it directly from wherever it is?

KenJackson 04-05-2008 10:59 PM

Aliases aren't in the path. They're in the environment.

Run the command alias with no arguments to get a list of currently defined aliases. Or run the command type temp to verify that temp really is aliased.

Are you calling the script from the command line? From cron? Via SSH? What error message do you get?

snowman81 04-06-2008 10:33 AM

The type temp command gives me this output
Code:

temp is aliased to `cat /home/jason/Desktop/scripts/test'
I'm trying to call it in a script with this line
Code:

var2=$(temp | awk '{print $4}')
And I get this error
Code:

line 6: temp: command not found

KenJackson 04-06-2008 12:07 PM

That's curious. I just tried a very similar thing here and it worked.

Are you executing the var2 assignment from the command line? Or is it in a script? If in a script, are you calling it from the command line?

What's even more curious is the reference to line 6 when 'temp' has but one line. It makes me wonder if there is some other 'temp' script somewhere that's getting called instead.

colucix 04-06-2008 02:39 PM

It seems to me that aliases cannot be inherited from the environment into shell scripts. However you can use aliases in a shell script if the alias definition is in your $HOME/.bashrc file and if you make your shell act as a login shell (in this case the .bashrc file is sourced). For example
Code:

#!/bin/bash -l
shopt -s expand_aliases
var2=$(temp | awk '{print $4}')
echo $var2

In the first line you have to add the -l option to bash. Furthermore the second line uses the shopt command to enable the expand_aliases option, otherwise aliases are not interpreted. Anyway there are a lot of reasons to not use aliases inside scripts and use functions instead. See Chapter 24 of the Advanced Bash Scripting Guide for a full treatment.


All times are GMT -5. The time now is 03:01 AM.