How do I execute a bash script from anywhere?
On UNIX, I read that moving the shell script to / usr / local / bin will allow you to execute the script from anywhere by simply typing "[scriptname] .sh" and hitting enter.
I have moved the script as normal user and root, but I cannot run it.
script:
#! bin/bash
echo "The current date and time is:"
date
echo "The total system uptime is"
uptime
echo "The users currently logged in are:"
who
echo "The current user is:"
who -m
exit 0
This is what happens when I try to move and then run the script:
[myusername@VDDK13C-6DDE885 ~]$ sudo mv sysinfo.sh /usr/local/bin
[myusername@VDDK13C-6DDE885 ~]$ sysinfo.sh
bash: sysinfo.sh: command not found
source to share
If you want to run your script everywhere you need to add it to your PATH
. Usually /usr/local/bin
found in every user's path, so it should work. So check if your system is /usr/local/bin
on your PATH
, on your terminal:
echo $PATH
You should see a lot of these ways (eg /bin
, /sbin
etc.). If it is not listed, you can add it. An even better solution is to keep all your scripts inside a directory like yours home
and add it to your path.
To add a directory to your path, you can change the init scripts shell
and add new directories, for example, if you are using a shell BASH
, you can create your own .bashrc
and add the line:
PATH=$PATH:/the_directory_you_want_to_add/:/another_directory/
This will add new directories to the existing ones PATH
.
source to share
You need to move it somewhere along the way. Try the following:
echo $PATH
I put / usr / local / bin, not listed.
I handle this by creating a bin directory in my $ HOME (i.e. mkdir ~/bin
) and adding it to my ~ / .bashrc file (create a file if you don't already have one):
export PATH=~/bin:$PATH
source to share
To run an executable from any directory:
1) Create a bin directory in your home directory and paste executable scripts into it.
[root@ip9-114-192-179 ~]# cd /home
[root@ip9-114-192-179 home]# mkdir bin
[root@ip9-114-192-179 home]#ls
bin cloud-init-0.7.4-10.el7.noarch.rpm cloud-user epel-release-7-11.noarch.rpm
2) Move your executable scripts to bin direcoty.
mv preeti.sh /home/bin
3) Now add it to your path variable.
[root@ip9-114-192-179 ~]# echo 'export PATH="$PATH:/home/bin"' >> /etc/profile
[root@ip9-114-192-179 ~]# source /etc/profile
[root@ip9-114-192-179 ~]# echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin:/home/bin
4) Check if this path is added to the path variable.
[root@ip9-114-192-179 ~]# echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin:/home/bin
5) Make sure the script is run from any random directory.
source to share