Why are the results from terminal and bash script different? [duplicate] - linux

This question already has answers here:
How to use aliases defined in .bashrc in other scripts?
(6 answers)
Closed 1 year ago.
USER#HOST:~:$ cat .bashrc
if [ -f /etc/bashrc ]; then
. /etc/bashrc
fi
# User specific aliases and functions
alias sudo='sudo -i'
USER#HOST:~:$ cat tmp.sh
#!/bin/bash
sudo env | grep PATH
USER#HOST:~:$ ./tmp.sh
PATH=/usr/bin:/bin:/usr/sbin:/sbin
USER#HOST:~:$ sudo env | grep PATH
PATH=/usr/python-3.8.2-r2/bin:/usr/jdk64/jdk1.8.0_112/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/bin:/root/bin
I put an alias setting in my .bashrc file.
When I test it through a terminal, it's okay.
But it seems to work differently when done with a script.
What's the difference here, and how can I test this through script?

The alias does not apply to the script. You'll see the equivalent if you use command to bypass alias expansion in the shell:
$ command sudo env | grep PATH

Related

bash command working from terminal but not from script [duplicate]

a.sh
#! /bin/sh
export x=/usr/local
we can do source ./a in command-line. But I need to do the export through shell script.
b.sh
#! /bin/sh
. ~/a.sh
no error... but $x in command-line will show nothing. So it didn't get export.
Any idea how to make it work?
a.sh
#! /bin/sh
export x=/usr/local
-----------
admin#client: ./a.sh
admin#client: echo $x
admin#client: <insert ....>
You can put export statements in a shell script and then use the 'source' command to execute it in the current process:
source a.sh
You can't do an export through a shell script, because a shell script runs in a child shell process, and only children of the child shell would inherit the export.
The reason for using source is to have the current shell execute the commands
It's very common to place export commands in a file such as .bashrc which a bash will source on startup (or similar files for other shells)
Another idea is that you could create a shell script which generates an export command as it's output:
shell$ cat > script.sh
#!/bin/sh
echo export foo=bar
^D
chmod u+x script.sh
And then have the current shell execute that output
shell$ `./script.sh`
shell$ echo $foo
bar
shell$ /bin/sh
$ echo $foo
bar
(note above that the invocation of the script is surrounded by backticks, to cause the shell to execute the output of the script)
Answering my own question here, using the answers above: if I have more than one related variable to export which use the same value as part of each export, I can do this:
#!/bin/bash
export TEST_EXPORT=$1
export TEST_EXPORT_2=$1_2
export TEST_EXPORT_TWICE=$1_$1
and save as e.g. ~/Desktop/TEST_EXPORTING
and finally $chmod +x ~/Desktop/TEST_EXPORTING
--
After that, running it with source ~/Desktop/TEST_EXPORTING bob
and then checking with export | grep bob should show what you expect.
Exporting a variable into the environment only makes that variable visible to child processes. There is no way for a child to modify the environment of its parent.
Another way you can do it (to steal/expound upon the idea above), is to put the script in ~/bin and make sure ~/bin is in your PATH. Then you can access your variable globally. This is just an example I use to compile my Go source code which needs the GOPATH variable to point to the current directory (assuming you're in the directory you need to compile your source code from):
From ~/bin/GOPATH:
#!/bin/bash
echo declare -x GOPATH=$(pwd)
Then you just do:
#> $(GOPATH)
So you can now use $(GOPATH) from within your other scripts too, such as custom build scripts which can automatically invoke this variable and declare it on the fly thanks to $(pwd).
script1.sh
shell_ppid=$PPID
shell_epoch=$(grep se.exec_start "/proc/${shell_ppid}/sched" | sed 's/[[:space:]]//g' | cut -f2 -d: | cut -f1 -d.)
now_epoch=$(($(date +%s%N)/1000000))
shell_start=$(( (now_epoch - shell_epoch)/1000 ))
env_md5=$(md5sum <<<"${shell_ppid}-${shell_start}"| sed 's/[[:space:]]//g' | cut -f1 -d-)
tmp_dir="/tmp/ToD-env-${env_md5}"
mkdir -p "${tmp_dir}"
ENV_PROPS="${tmp_dir}/.env"
echo "FOO=BAR" > "${ENV_PROPS}"
script2.sh
shell_ppid=$PPID
shell_epoch=$(grep se.exec_start "/proc/${shell_ppid}/sched" | sed 's/[[:space:]]//g' | cut -f2 -d: | cut -f1 -d.)
now_epoch=$(($(date +%s%N)/1000000))
shell_start=$(( (now_epoch - shell_epoch)/1000 ))
env_md5=$(md5sum <<<"${shell_ppid}-${shell_start}"| sed 's/[[:space:]]//g' | cut -f1 -d-)
tmp_dir="/tmp/ToD-env-${env_md5}"
mkdir -p "${tmp_dir}"
ENV_PROPS="${tmp_dir}/.env"
source "${ENV_PROPS}"
echo $FOO
./script1.sh
./script2.sh
BAR
It persists for the scripts run in the same parent shell, and it prevents collisions.

Bash script tee command syntax issue

I want to echo the following line at the end of ~/.profile file using tee command:
export PATH="$HOME/.local/bin:$PATH"
To do this my bash script looks like this
#!/bin/bash
path_env="export PATH="$HOME/.local/bin:$PATH""
echo $path_env| sudo tee -a $HOME/.profile > /dev/null
But whenever I am executing the script it is also executing $PATH and $HOME value and inserts that in ~./profile file which I do not want. I only want the exact line to be passed by the bash script instead of replacing $PATH and $HOME with its own values.
I only want the exact line to be passed by the bash script instead of replacing $PATH and $HOME with its own values.
Och, right, so do not expand it. Quoting.
path_env='export PATH="$HOME/.local/bin:$PATH"'
echo "$path_env" | sudo tee -a "$HOME/.profile" > /dev/null

Execute bash on logon and add alias

When I login to a Linux server per Putty, I want to execute the bash (because the default shell is another) and after that adding an alias.
I tried several combinations of putting exec bash in the .profile and adding alias foo='echo foo' into .bash_profile. But I didn't find out the correct combination. Either the alias wasn't set, or the bash wasn't executed.
So, the question is, in which of these files:
.profile
.bashrc
.bash_profile
do I have to put these commands:
exec bash
alias foo='echo foo'
to run the bash shell and have access to my alias every time I login to the server?
edit: We're using all the same user to login. But I want to execute the bash and adding the alias only for my remote machine. I do already have a suitable if statement for that. I only have to know, where to put these commands!
edit2:
What I have so far in my .profile:
if [ $(who -m | awk '{print $NF}' | grep "myHostName" | wc -l) -eq 1 ]
then
exec bash
alias foo='echo foo'
fi
This will execute the bash for only my user. But the alias will be ignored, since I'm starting a new shell and the alias will be probably set in the old shell...
Going to go out on a limb and guess you want to do this because your default shell isn't bash. Don't. Just change your default shell
> chsh -s /bin/bash
Then put
alias foo='echo foo'
In either ~/.bashrc or ~/.bash_profile
If multiple users are using the same account, you can try to do the following. While logged in, run
> who -a | grep $(ps -p $PPID -o ppid=) | awk '{print $NF}'
This may be system dependent, but on a couple I tried it on, this will get location you're logged in from. Once you have that output, do the following
if [[ $(who -a | grep $(ps -p $PPID -o ppid=) | awk '{print $NF}') == output ]]; then
alias foo='echo foo'
done
If you're ssh-ing from multiple computers, then I don't think there is any way to do what you want. Simplest would be to make your own file in the home directory, and then source it manually each time you log in.
e.g.
> touch myfile.txt
> echo "alias foo='echo foo'" >> myfile.txt
> source myfile.txt
> foo
foo
So you would just have to run source myfile.txt each time you log in or just have putty source it by default.
Okay, finally I figured it out by myself with the great help of BroSlow.
I wrote the following to my .profile:
if [ $(who -m | awk '{print $NF}' | grep "myHostName" | wc -l) -eq 1 ]
then
exec bash
fi
and the other part to the .bash_profile:
if [ $(who -m | awk '{print $NF}' | grep "myHostName" | wc -l) -eq 1 ]
then
alias foo='echo foo'
fi
This solved my problem!
On logon, the .profile will be sourced automatically and will execute the bash.
After that the .bash_profile will be sourced due to the fact, that the bash shell will source it's own profile.
However: thanks a lot for the support!
To set up alias in startup change your .bash_profile
Add alias to bash profile:
$ cd
$ sudo nano .bash_profile
$ alias ALIAS_NAME='COMMAND'
Update bash profile
$ source ~/.bash_profile

Set Env Var and Access From Bash Script

This is probably a really stupid question, but how do I set an Environment Variable in Bash, then access it in a shell script?
kkeiper#machine:/home/kkeiper $ export APIKEY="adsf"
In bash script
#!/bin/bash
echo $APIKEY; # prints a blank line
echo $(env | grep APIKEY); # wouldn't return APIKEY even if it did work, but this also prints a blank string
What you show should work! It does for me:
$ export APIKEY="asfw"
$ cat script.sh
#!/bin/bash
echo $APIKEY
env | grep APIKEY
$ bash -x script.sh
+ echo asfw
asfw
+ env
+ grep APIKEY
APIKEY=asfw
$ sudo bash script.sh
Password:
$
Note that you don't need the semicolons or the echo $(...) notation in the script — but they don't do any damage either.
(Tested Mac OS X 10.9 Mavericks, Bash 3.2.51. However, I don't expect it to matter. Only true Bourne shells don't support the export VAR=value notation — and you'll have to look hard to find a shell with that limitation these days; Solaris /bin/sh, perhaps.)
Example with sudo added after question in comments. Yes, sudo unsets stray environment variables such as APIKEY.
More notes on sudo:
$ env | wc -l
24
$ env | grep APIKEY
APIKEY=asfw
$ cat script.sh
#!/bin/bash
echo $APIKEY
env | grep APIKEY
env | wc -l
$ bash script.sh
asfw
APIKEY=asfw
23
$ sudo bash script.sh
18
$
One day, I'll investigate the what and the why for the difference between 24 and 23 environment variables without sudo being involved, but clearly sudo eliminated a number of variables (5 or 6, including APIKEY specifically).
How to ensure that environment variables are preserved?
If you know which ones need to be preserved, then:
The sudo man page says:
-E The -E (preserve environment) option will override the env_reset option
in sudoers(5)). It is only available when either the matching command
has the SETENV tag or the setenv option is set in sudoers(5).
You can arrange to relay the environment variables to the commands environment:
$ sudo -E bash script.sh
Password:
asfw
APIKEY=asfw
26
$ sudo bash -c "APIKEY='$APIKEY' bash script.sh"
asfw
APIKEY=asfw
SUDO_COMMAND=/bin/bash -c APIKEY='asfw' bash script.sh
19
$
The appearance of SUDO_COMMAND in the environment is interesting.
(Note that the bash script.sh notation is only needed because I've not made script.sh executable. If it was executable, I could type either script.sh or ./script.sh depending on whether it is in a directory on my $PATH or not.)

Alias with variable in bash [duplicate]

This question already has answers here:
Make a Bash alias that takes a parameter?
(24 answers)
Closed 5 years ago.
I want to create an alias in bash like this:
alias tail_ls="ls -l $1 | tail"
Thus, if somebody types:
tail_ls /etc/
it will only show the last 10 files in the directory.
But $1 does not seem to work for me. Is there any way I can introduce variables in bash.
I'd create a function for that, rather than alias, and then exported it, like this:
function tail_ls { ls -l "$1" | tail; }
export -f tail_ls
Note -f switch to export: it tells it that you are exporting a function. Put this in your .bashrc and you are good to go.
alias tail_ls='_tail_ls() { ls -l "$1" | tail ;}; _tail_ls'
The solution of #maxim-sloyko did not work, but if the following:
In ~/.bashrc add:
sendpic () { scp "$#" mina#foo.bar.ca:/www/misc/Pictures/; }
Save the file and reload
$ source ~/.bashrc
And execute:
$ sendpic filename.jpg
original source: http://www.linuxhowtos.org/Tips%20and%20Tricks/command_aliases.htm
You can define $1 with set, then use your alias as intended:
$ alias tail_ls='ls -l "$1" | tail'
$ set mydir
$ tail_ls
tail_ls() { ls -l "$1" | tail; }
If you are using the Fish shell (from http://fishshell.com ) instead of bash, they write functions a little differently.
You'll want to add something like this to your ~/.config/fish/config.fish which is the equivalent of your ~/.bashrc
function tail_ls
ls -l $1 | tail
end

Resources