How to run a shell script just by typing its name? - shell

I am very stuck on a task for my controlled assessment. I have been asked to create a shell script in nano that echoes hello world and hello $user. I have set the script to be executable. (chmod 755 Script1 and chmod +x Script1). I have been tasked to be able to make the script run just by typing 'Script1' , I do not know how to set the path to do this. Any help would be greatly appreciated.

Basically you need to have it in the PATH environment variable.
Suppose it's in a folder on /a/b/folder/script.sh, try:
PATH=$PATH:/a/b/folder/
This tells the shell to look for executables there when looking for commands to run.
To make sure it's always executable you have several options:
Set the path variable in your profile using ~/.bashrc (sets it for bash, commonly done in ubuntu, which is what I use) or ~/.profile.
Set it globally using /etc/environment or others...
Move the folder to a folder already on your path (echo $PATH to see what's there already).
Note that these files are source-ed on different stages and persist on different environments.
For even more information read this.
TIP: To test that you've set the file correctly, we'll take ~/.bashrc as an example, you can use source ~/.bashrc and everything in ~/.bashrc will be loaded. That way you can be sure it won't mess things up next time you log in.

Alias the script in .bash_profile
in home path open the .bash_profile file and add the following entry,
alias Script1='/path/to/Script1'
Then reload the bash by,
. .bash_profile
After that try to call the script by using just its name. i.e, Script1

Related

How to properly write a bash executable file

I am having some issue in writing a simple executable .sh file via bash.
The order of operation as soon as I open a terminal (ctrl+alt+T) are:
pc:~$ roscd
pc:~/catkin_docking_ws/devel$ cd ..
pc:~/catkin_docking_ws$ cd devel/lib/tuginterface/
pc:~/catkin_docking_ws/devel/lib/tuginterface$ ./tuginterface
I have been investigating this small issue and came across this source which advises to change and rename the project as an alias and that is exactly what I tried to do:
alias proj="roscd"
alias proj2="cd .."
alias proj3="cd devel/lib/tuginterface/"
alias exec="./tuginterface"
My current executable file after many trials is:
#!/bin/bash
alias proj="roscd"
alias proj2="cd .."
alias proj3="cd devel/lib/tuginterface/"
alias exec="./tuginterface"
But it still does not work.
The same post advises to create a script and after that an alias in the startup file.
Please advise on how to solve this problem and sorry if it is a simple question but I don't seem to catch the mistake I am making.
The script doesn't need to define aliases. Aliases are commands that you can type yourself. The script can just execute the commands directly.
#!/bin/bash
cd ~/catkin_docking_ws/devel/lib/tuginterface
./tuginterface
I've combined the three cd commands into one that jumps straight to the correct directory.
"But I thought cd doesn't work in shell scripts?"
It depends what you're looking for. When a script changes directory it affects later commands in the script, so in that respect it does work. The change of directory is only inside the script, though. The person calling the script won't see the directory change. Their current directory is unaffected.

How to update PATH to find nvcc for CUDA 8.0? [duplicate]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 2 years ago.
Improve this question
On Linux, how can I add a directory to the $PATH so it remains persistent across different sessions?
Background
I'm trying to add a directory to my path so it will always be in my Linux path. I've tried:
export PATH=$PATH:/path/to/dir
This works, however each time I exit the terminal and start a new terminal instance, this path is lost, and I need to run the export command again.
How can I do it so this will be set permanently?
You need to add it to your ~/.profile or ~/.bashrc file.
export PATH="$PATH:/path/to/dir"
Depending on what you're doing, you also may want to symlink to binaries:
cd /usr/bin
sudo ln -s /path/to/binary binary-name
Note that this will not automatically update your path for the remainder of the session. To do this, you should run:
source ~/.profile
or
source ~/.bashrc
There are multiple ways to do it. The actual solution depends on the purpose.
The variable values are usually stored in either a list of assignments or a shell script that is run at the start of the system or user session. In case of the shell script you must use a specific shell syntax and export or set commands.
System wide
/etc/environment List of unique assignments. Allows references. Perfect for adding system-wide directories like /usr/local/something/bin to PATH variable or defining JAVA_HOME. Used by PAM and systemd.
/etc/environment.d/*.conf List of unique assignments. Allows references. Perfect for adding system-wide directories like /usr/local/something/bin to PATH variable or defining JAVA_HOME. The configuration can be split into multiple files, usually one per each tool (Java, Go, and Node.js). Used by systemd that by design do not pass those values to user login shells.
/etc/xprofile Shell script executed while starting X Window System session. This is run for every user that logs into X Window System. It is a good choice for PATH entries that are valid for every user like /usr/local/something/bin. The file is included by other script so use POSIX shell syntax not the syntax of your user shell.
/etc/profile and /etc/profile.d/* Shell script. This is a good choice for shell-only systems. Those files are read only by shells in login mode.
/etc/<shell>.<shell>rc. Shell script. This is a poor choice because it is single shell specific. Used in non-login mode.
User session
~/.pam_environment. List of unique assignments, no references allowed. Loaded by PAM at the start of every user session irrelevant if it is an X Window System session or shell. You cannot reference other variables including HOME or PATH so it has limited use. Used by PAM.
~/.xprofile Shell script. This is executed when the user logs into X Window System system. The variables defined here are visible to every X application. Perfect choice for extending PATH with values such as ~/bin or ~/go/bin or defining user specific GOPATH or NPM_HOME. The file is included by other script so use POSIX shell syntax not the syntax of your user shell. Your graphical text editor or IDE started by shortcut will see those values.
~/.profile, ~/.<shell>_profile, ~/.<shell>_login Shell script. It will be visible only for programs started from terminal or terminal emulator. It is a good choice for shell-only systems. Used by shells in login mode.
~/.<shell>rc. Shell script. This is a poor choice because it is single shell specific. Used by shells in non-login mode.
Notes
GNOME on Wayland starts a user login shell to get the environment. It effectively uses the login shell configurations ~/.profile, ~/.<shell>_profile, ~/.<shell>_login files.
Man pages
environment
environment.d https://linux.die.net/man/1/environment.d
bash
dash
Distribution-specific documentation
Ubuntu
Arch Linux
Related
Difference between Login Shell and Non-Login Shell?
In Ubuntu, edit /etc/environment. Its sole purpose is to store environment variables. Originally the $PATH variable is defined here.
This is a paste from my /etc/environment file:
PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games"
So you can just open up this file as root and add whatever you want.
For immediate results,
Run (try as normal user and root):
source /etc/environment && export PATH
If you use Z shell (zsh), add this line right after the comments in /etc/zsh/zshenv file:
source /etc/environment
I encountered this little quirk on Ubuntu 15.10 (Wily Werewolf), but if your zsh is not getting the correct PATH, this could be why.
For Bash, you can put the export declaration in ~/.bashrc. For example, my .bashrc contains this line:
export PATH=/var/lib/gems/1.8/bin:/home/ash/.bin:$PATH
You may set $PATH permanently in two ways.
To set the path for a particular user:
You may need to make the entry in file .bash_profile in the home directory for the user.
E.g, in my case I will set the java path in the Tomcat user profile*
echo "export PATH=$PATH:/path/to/dir" >> /home/tomcat/.bash_profile
To set a common path for all system users, you may need to set the path like this:
echo "export PATH=$PATH:/path/to/dir" >> /etc/profile
You can use on CentOS or Red Hat Linux (RHEL) for the local user:
echo $"export PATH=\$PATH:$(pwd)" >> ~/.bash_profile
This adds the current directory (or you can use another directory) to the PATH. This makes it permanent, but it takes effect at the next user logon.
If you don't want do a re-logon, then you can use:
source ~/.bash_profile
That reloads the # User specific environment and startup programs. This comment is present in file .bash_profile.
You can also set it permanently, editing one of these files:
/etc/profile (for all users)
~/.bash_profile (for current user)
~/.bash_login (for current user)
~/.profile (for current user)
You can also use /etc/environment to set a permanent PATH environment variable, but it does not support variable expansion.
Extracted from: Linux: Añadir ruta al PATH
I think the most elegant way is:
Add this in the ~/.bashrc file.
Run this command:
gedit ~/.bashrc
Add your path inside it:
export PATH=$PATH:/opt/node/bin
source ~/.bashrc
(Ubuntu)
Modify the "/etc/profile" file:
vi /etc/profile
Press the I key to enter editing mode and move the cursor to the end of the file. Additional entries:
export PATH=$PATH:/path/to/dir;
Press the Esc key to exit edit mode, and :wq to save the file.
Make the configuration effective
source /etc/profile
Explanation:
The profile file works for all users. If you want it to be valid only for the active user, change the ".bashrc" file.
I stumbled across this question yesterday when searching for a way to add a folder containing my own scripts to the PATH - and was surprised to find out that my own ~/.profile file (on Linux Mint 18.1) already contained this:
# set PATH so it includes user's private bin if it exists
if [ -d "$HOME/bin" ] ; then
PATH="$HOME/bin:$PATH"
fi
Thus, all I had to do was create the folder ~/bin and put my scripts there.
You can add that line to your console configuration files (e.g., .bashrc, or to .profile).
After so much research, I found a simple solution for this (I am using Elementary OS), inspired by Flutter – Step by Step Installation on Linux – Ubuntu.
Run the following command to open the .bashrc file in edit mode. (You
may also use vi or any other editor).
~$ sudo nano ~/.bashrc
Add the following line at the end of the file and save.
export PATH="[FLUTTER_SDK_PATH]/flutter/bin:$PATH"
For example:
export PATH="/home/rageshl/dev/flutter/bin:$PATH"
I believe this is the permanent solution for setting the path in Flutter in a Ubuntu distribution.
It can be directly added by using the following command:
echo 'export PATH=$PATH:/new/directory' >> ~/.zshrc
source ~/.zshrc
One way to add a permanent path, which worked for me, is:
cd /etc/profile.d
touch custom.sh
vi custom.sh
export PATH=$PATH:/path according to your setting/
Restart your computer and here we go; the path will be there permanently.
Add script file [name_of_script].sh to the /etc/profile.d folder with the line:
export PATH=$PATH:/dir
Every script within the /etc/profile.d folder is automatically executed by /etc/profile on login.
My answer is in reference to the setting up of a Go environment on Ubuntu Linux (amd64). I have faced the same trouble of setting the path of environment variables (GOPATH and GOBIN), losing it on terminal exit and rebuilding it using the source <file_name> every time.
The mistake was to put the path (GOPATH and GOBIN) in ~/.bash_profile file. After wasting a few good hours, I found that the solution was to put GOPATH and GOBIN in the ~/.bash_rc file in the manner:
export GOPATH=$HOME/go
export GOBIN=$GOPATH/bin
export PATH=$PATH:$GOPATH:$GOBIN
And in doing so, the Go installation worked fine and there were no path losses.
The reason with which this issue can be related is that settings for non-login shells, like your Ubuntu terminal or GNOME terminal where we run the Go code, are taken from the ~./bash_rc file and the settings for login shells are taken from ~/.bash_profile file. And from the ~/.profile file if the ~/.bash_profile file is unreachable.
The files where you add the export command depends on if you are in login-mode or non-login-mode.
If you are in login-mode, the files you are looking for are either /etc/bash or /etc/bash.bashrc.
If you are in non-login-mode, you are looking for the file /.profile or for the files within the directory /.profiles.d
The files mentioned above is where the system variables are.
Permanently add to the PATH variable
Global:
echo "export PATH=$PATH:/new/path/variable" >> /etc/profile
Local (for the current user only):
echo "export PATH=$PATH:/new/path/variable" >> ~/.profile
For global, restart. For local, relogin.
Example
Before:
$ cat /etc/profile
#!/bin/sh
export PATH=/usr/bin:/usr/sbin:/bin:/sbin
After:
$ cat /etc/profile
#!/bin/sh
export PATH=/usr/bin:/usr/sbin:/bin:/sbin
export PATH=/usr/bin:/usr/sbin:/bin:/sbin:/new/path/variable
Alternatively you can just edit file "profile":
$ cat /etc/profile
#!/bin/sh
export PATH=/usr/bin:/usr/sbin:/bin:/sbin:/new/path/variable
Another way (thanks gniourf_gniourf):
echo 'PATH=$PATH:/new/path/variable' >> /etc/profile
You shouldn't use double quotes here! echo 'export
PATH=$PATH:/new/path/variable'... And by the way, the export keyword
is very likely useless as the PATH variable is very likely already
marked as exported. – gniourf_gniourf
Zues77 has the right idea. The OP didn't say "How can I hack my way through this?". The OP wanted to know how to permanently append to $PATH:
sudo nano /etc/profile
This is where it is set for everything and is the best place to change it for all things needing $PATH.
Let's say you're running macOS. You have a binary you trust and would like to make available across your system, but don't necessarily want the directory in which the binary is to be added to your PATH.
You can opt to copy/move the binary to /usr/local/bin, which should already be in your PATH. This will make the binary executable like any other binary you may already have access to in your terminal.
The simplest way is the following line,
PATH="<directory you want to include>:$PATH"
in your .bashrc file in the home directory.
It will not get reset even if you close the terminal or reboot your PC. It's permanent.
This is a one-liner. It adds a line to the .bashrc. That line is going to check if the directory has already been added to the path and append if not. This will prevent duplicating your directory in the path every time you source .bashrc.
echo "[[ \":\$PATH:\" != *\":$(pwd)/path/to/add:\"* ]] && export PATH=\"\${PATH:+\${PATH}}:$(pwd)/path/to/add\"" >> ~/.bashrc
source ~/.bashrc
I think the most elegant way is:
Add this in the ~./bashrc file:
if [ -d "new-path" ]; then
PATH=$PATH:new-path
fi
source *~/.bashrc*
(Ubuntu)
For a Debian distribution, you have to:
edit file ~/.bashrc. E.g: vim ~/.bashrc
add export PATH=$PATH:/path/to/dir
then restart your computer. Be aware that if you edit file ~/.bashrc as root, your environment variable you added will work only for root

Raspbian: Reset Bash environment variables

I was trying to get a crontab working on my Raspberry PI and I think I messed up my environment variables. I can execute a file from the GUI by right-clicking and choosing execute. However I cannot get the same file to run from command line. I can use ls to see the file (ChromeTab.sh), but when I type ChromeTab.sh, I get "bash: ChromeTab.sh: command not found".
I think I messed up my environment variables when I put this in the crontab.
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
I followed the examples in Script doesn't run via crontab but works fine standalone.
Any idea what I'm doing wrong?
UPDATE:
OK,
Let me clarify what efforts I took on my part BEFORE posting my question on stackoverflow before getting anymore downvotes.
First of all thanks S. Adam Nissley for your suggestions.
In answer to your steps listed above.
Running this from home path, or fully qualified path does Not work as stated.
Error: bash: ChromeTab.sh: command not found
./ChromeTab.sh
I have also ensured read/write and execute permissions on the file with
chmod +x ./ChromeTab.sh
Also, my bash script starts off with the following shebang
#!/bin/sh
So, what i'm trying to say is, regardless of using crontab or not the issue at hand is that I can not even execute the script from command line. This started happening after I was messing around with the environment variables in the crontab. I'm looking for a way to revert to the situation where I can at least run/execute bash commands from the terminal.
The only way I can effectively execute this script is (right-click execute) through the GUI.
Assuming you are in the same directory as your script, you should just be able to enter
./ChromeTab.sh
If it does not execute, make sure it is executable with the command
chmod +x ./ChromeTab.sh
Or
chmod 755 ./ChromeTab.sh
And if it still won't execute, make sure it has an appropriate hashbang on the very first line of the script like #!/bin/sh or #!/bin/bash
When you add it to your crontab, make sure it has the full path like
/home/pi/bin/ChromeTab.sh <br/>
EDIT: Default PATH and SHELL for Raspbian
You can check your PATH and SHELL environmental variables from the command line as follows:
echo $SHELL
echo $PATH
The default PATH for Rasbian is:
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/games:/usr/games
And the default SHELL is:
/bin/bash
So if you need to set those it is as simple as:
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/games:/usr/games
SHELL=/bin/bash
If you are having other issues with your environment, you may want to disable some of your local settings to see if the problem is in your profile. You can list all files with ls -a, which includes hidden files. Raspbian typically has a .bashrc and a .profile in each user's home directory. To disable them simple rename them:
mv .bashrc .bashrc_disabled
mv .profile .profile_disabled
If that solves the problem, you can inspect the files and make the necessary corrections before renaming them back to their original names.

Creating aliases in .bash_profile that run a shell script

So I have a script called spotlyrics.sh that I want to be able to run using the command "lyrics" in the terminal.
I have opened up my .bash_profile and am wondering how I can create the alis which 1) finds the script and then 2) executes it
The file is inside a folder called bash at the following path
/Users/username/Documents/bash
What I have so far (inside my bash profile), which doesn't work because I guess it's not "executing" the script.
alias spotlyrics=“/Users/username/Documents/bash/spotlyrics.sh“
I get the following error when running "spotlyrics" in the terminal:
-bash: “/Users/username/Documents/bash/spotlyrics.sh“: No such file or directory
Would love some help, thanks!
You've been editing your .bash_profile with something that is not a proper text editor. The quotation marks are not ASCII, and therefore not actually quotation marks as far as the shell is concerned.
Instead of beating around the bush with aliasing a script to a name it mostly already has, why not put the script in a directory in PATH and let it be its own command?
mkdir ~/bin
echo 'PATH+=:$HOME/bin' >> ~/.bashrc
mv "/path/to/spotlyrics.sh" ~/bin/spotlyrics && chmod +x ~/bin/spotlyrics
Then restart the shell (log out and back in) and you won't need the alias.
Well, the shell scripts are not executable by just calling it's name, they should be run using "source" command(in case of not c-shell, dot command(.) can also be used).So while adding an alias in .bashrc or .bash_profile for running a shell script append source command before the path to the shell script.
In your case probably this should work:`
alias spotlyrics='source /Users/username/Documents/bash/spotlyrics.sh'`
Please let me know if it doesn't work. Because it worked for me.

How do I execute a bash script in Terminal?

I have a bash script like:
#!/bin/bash
echo Hello world!
How do I execute this in Terminal?
Yet another way to execute it (this time without setting execute permissions):
bash /path/to/scriptname
$prompt: /path/to/script and hit enter. Note you need to make sure the script has execute permissions.
cd to the directory that contains the script, or put it in a bin folder that is in your $PATH
then type
./scriptname.sh
if in the same directory or
scriptname.sh
if it's in the bin folder.
You could do:
sh scriptname.sh
This is an old thread, but I happened across it and I'm surprised nobody has put up a complete answer yet. So here goes...
The Executing a Command Line Script Tutorial!
Q: How do I execute this in Terminal?
The answer is below, but first ... if you are asking this question, here are a few other tidbits to help you on your way:
Confusions and Conflicts:
The Path
Understanding The Path (added by tripleee for completeness) is important. The "path" sounds like a Zen-like hacker koan or something, but it is simply a list of directories (folders) that are searched automatically when an unknown command is typed in at the command prompt. Some commands, like ls may be built-in's, but most commands are actually separate small programs. (This is where the "Zen of Unix" comes in ... "(i) Make each program do one thing well.")
Extensions
Unlike the old DOS command prompts that a lot of people remember, you do not need an 'extension' (like .sh or .py or anything else), but it helps to keep track of things. It is really only there for humans to use as a reference and most command lines and programs will not care in the least. It won't hurt. If the script name contains an extension, however, you must use it. It is part of the filename.
Changing directories
You do not need to be in any certain directory at all for any reason. But if the directory is not on the path (type echo $PATH to see), then you must include it. If you want to run a script from the current directory, use ./ before it. This ./ thing means 'here in the current directory.'
Typing the program name
You do not need to type out the name of the program that runs the file (BASH or Python or whatever) unless you want to. It won't hurt, but there are a few times when you may get slightly different results.
SUDO
You do not need sudo to do any of this. This command is reserved for running commands as another user or a 'root' (administrator) user. Running scripts with sudo allows much greater danger of screwing things up. So if you don't know the exact reason for using sudo, don't use it. Great post here.
Script location ...
A good place to put your scripts is in your ~/bin folder.
You can get there by typing
# A good place to put your scripts is in your ~/bin folder.
> cd ~/bin # or cd $HOME/bin
> ls -l
You will see a listing with owners and permissions. You will notice that you 'own' all of the files in this directory. You have full control over this directory and nobody else can easily modify it.
If it does not exist, you can create one:
> mkdir -p ~/bin && cd ~/bin
> pwd
/Users/Userxxxx/bin
A: To "execute this script" from the terminal on a Unix/Linux type system, you have to do three things:
1. Tell the system the location of the script. (pick one)
# type the name of the script with the full path
> /path/to/script.sh
# execute the script from the directory it is in
> ./script.sh
# place the script in a directory that is on the PATH
> script.sh
# ... to see the list of directories in the path, use:
> echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
# ... or for a list that is easier to read:
> echo -e ${PATH//:/\\n}
# or
> printf "%b" "${PATH//:/\\n}"
/usr/local/sbin
/usr/local/bin
/usr/sbin
/usr/bin
/sbin
/bin
2. Tell the system that the script has permission to execute. (pick one)
# set the 'execute' permissions on the script
> chmod +x /path/to/script.sh
# using specific permissions instead
# FYI, this makes these scripts inaccessible by ANYONE but an administrator
> chmod 700 /path/to/script.sh
# set all files in your script directory to execute permissions
> chmod +x ~/bin/*
There is a great discussion of permissions with a cool chart here.
3. Tell the system the type of script. (pick one)
Type the name of the program before the script. (Note: when using this method, the execute(chmod thing above) is not required
> bash /path/to/script.sh
...
> php /path/to/script.php
...
> python3 /path/to/script.py
...
Use a shebang, which I see you have (#!/bin/bash) in your example. If you have that as the first line of your script, the system will use that program to execute the script. No need for typing programs or using extensions.
Use a "portable" shebang. You can also have the system choose the version of the program that is first in the PATH by using #!/usr/bin/env followed by the program name (e.g. #!/usr/bin/env bash or #!/usr/bin/env python3). There are pros and cons as thoroughly discussed here.
Note: This "portable" shebang may not be as portable as it seems. As with anything over 50 years old and steeped in numerous options that never work out quite the way you expect them ... there is a heated debate. The most recent one I saw that is actually quite different from most ideas is the "portable" perl-bang:
#!/bin/sh
exec perl -x "$0" "$#"
#!perl
Firstly you have to make it executable using: chmod +x name_of_your_file_script.
After you made it executable, you can run it using ./same_name_of_your_file_script
Change your directory to where script is located by using cd command
Then type
bash program-name.sh
And yet one more way
. /path/to/script
What is the meaning of the dot?
If you are in a directory or folder where the script file is available then simply change the file permission in executable mode by doing
chmod +x your_filename.sh
After that you will run the script by using the following command.
$ sudo ./your_filename.sh
Above the "." represent the current directory.
Note!
If you are not in the directory where the bash script file is present then you change the directory where the file is located by using
cd Directory_name/write the complete path
command. Otherwise your script can not run.

Resources