[bash] How do I run a shell script without using "sh" or "bash" commands?

I have a shell script which I want to run without using the "sh" or "bash" commands. For example:

Instead of: sh script.sh

I want to use: script.sh

How can I do this?

P.S. (i) I don't use shell script much and I tried reading about aliases, but I did not understand how to use them.

(ii) I also read about linking the script with another file in the PATH variables. I am using my university server and I don't have permissions to create a file in those locations.

This question is related to bash shell alias sh

The answer is


Here is my backup script that will give you the idea and the automation:

Server: Ubuntu 16.04 PHP: 7.0 Apache2, Mysql etc...

# Make Shell Backup Script - Bash Backup Script
    nano /home/user/bash/backupscript.sh
        #!/bin/bash
        # Backup All Start
        mkdir /home/user/backup/$(date +"%Y-%m-%d")
        sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/etc_rest.zip /etc -x "*apache2*" -x "*php*" -x "*mysql*"
        sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/etc_apache2.zip /etc/apache2
        sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/etc_php.zip /etc/php
        sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/etc_mysql.zip /etc/mysql
        sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/var_www_rest.zip /var/www -x "*html*"
        sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/var_www_html.zip /var/www/html
        sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/home_user.zip /home/user -x "*backup*"
        # Backup All End
        echo "Backup Completed Successfully!"
        echo "Location: /home/user/backup/$(date +"%Y-%m-%d")"

    chmod +x /home/user/bash/backupscript.sh
    sudo ln -s /home/user/bash/backupscript.sh /usr/bin/backupscript

change /home/user to your user directory and type: backupscript anywhere on terminal to run the script! (assuming that /usr/bin is in your path)


You can type sudo install (name of script) /usr/local/bin/(what you want to type to execute said script)

ex: sudo install quickcommit.sh /usr/local/bin/quickcommit enter password

now can run without .sh and in any directory


Enter "#!/bin/sh" before script. Then save it as script.sh for example. copy it to $HOME/bin or $HOME/usr/bin
The directory can be different on different linux distros but they end with 'bin' and are in home directory cd $HOME/bin or $HOME/usr/bin
Type chmod 700 script.sh
And you can run it just by typing run.sh on terminal. If it not work, try chmod +x run.sh instead of chmod 700 run.sh


Make any file as executable


Let's say you have an executable file called migrate_linux_amd64 and you want to run this file as a command like "migrate"

  1. First test the executable file from the file location:
[oracle@localhost]$ ./migrate.linux-amd64 
Usage: migrate OPTIONS COMMAND [arg...]
       migrate [ -version | -help ]

Options:
  -source          Location of the migrations (driver://url)
  -path            Shorthand for -source=file://path 
  -database        Run migrations against this database (driver://url)
  -prefetch N      Number of migrations to load in advance before executing (default 10)
  -lock-timeout N  Allow N seconds to acquire database lock (default 15)
  -verbose         Print verbose logging
  -version         Print version
  -help            Print usage

Commands:
  goto V       Migrate to version V
  up [N]       Apply all or N up migrations
  down [N]     Apply all or N down migrations
  drop         Drop everyting inside database
  force V      Set version V but don't run migration (ignores dirty state)
  version      Print current migration version
  1. Make sure you have execute privileges on the file
    -rwxr-xr-x 1 oracle oinstall 7473971 May 18 2017 migrate.linux-amd64
    if not, run chmod +x migrate.linux-amd64

  2. Then copy your file to /usr/local/bin. This directory is owned by root, use sudo or switch to root and perform the following operation

sudo cp migrate.linux-amd64 /usr/local/bin
sudo chown oracle:oracle /user/local/bin/migrate.linux.amd64
  1. Then create a symbolic link like below
sudo ln /usr/local/bin/migrate.linux.amd64 /usr/local/bin/migrate
sudo chown oracle:oracle /usr/local/bin/migrate
  1. Finally add /usr/local/bin to your path or user profile
export PATH = $PATH:/usr/local/bin
  1. Then run the command as "migrate"
[oracle@localhost]$ migrate
Usage: migrate OPTIONS COMMAND [arg...]
       migrate [ -version | -help ]

Options:
  -source          Location of the migrations (driver://url)
  -path            Shorthand for -source=file://path 
  -database        Run migrations against this database (driver://url)
  -prefetch N      Number of migrations to load in advance before executing (default 10)
  -lock-timeout N  Allow N seconds to acquire database lock (default 15)
  -verbose         Print verbose logging
  -version         Print version
  -help            Print usage

Commands:
  goto V       Migrate to version V
  up [N]       Apply all or N up migrations
  down [N]     Apply all or N down migrations
  drop         Drop everyting inside database
  force V      Set version V but don't run migration (ignores dirty state)
  version      Print current migration version

These are the prerequisites of directly using the script name:

  1. Add the shebang line (#!/bin/bash) at the very top.
  2. Use chmod u+x scriptname to make the script executable (where scriptname is the name of your script).
  3. Place the script under /usr/local/bin folder.
    • Note: I suggest placing it under /usr/local/bin because most likely that path will be already added to your PATH variable.
  4. Run the script using just its name, scriptname.

If you don't have access to /usr/local/bin then do the following:

  1. Create a folder in your home directory and call it bin.

  2. Do ls -lA on your home directory, to identify the start-up script your shell is using. It should be either .profile or .bashrc.

  3. Once you have identified the start up script, add the following line:

    PATH="$PATH:$HOME/bin"
    
  4. Once added, source your start-up script or log out and log back in.

    To source, put . followed by a space and then your start-up script name, e.g. . .profile or . .bashrc

  5. Run the script using just its name, scriptname.


You have to enable the executable bit for the program.

chmod +x script.sh

Then you can use ./script.sh

You can add the folder to the PATH in your .bashrc file (located in your home directory). Add this line to the end of the file:

export PATH=$PATH:/your/folder/here

Just:

/path/to/file/my_script.sh

Just make sure it is executable, using chmod +x. By default, the current directory is not on your PATH, so you will need to execute it as ./script.sh - or otherwise reference it by a qualified path. Alternatively, if you truly need just script.sh, you would need to add it to your PATH. (You may not have access to modify the system path, but you can almost certainly modify the PATH of your own current environment.) This also assumes that your script starts with something like #!/bin/sh.

You could also still use an alias, which is not really related to shell scripting but just the shell, and is simple as:

alias script.sh='sh script.sh'

Which would allow you to use just simply script.sh (literally - this won't work for any other *.sh file) instead of sh script.sh.


In this example the file will be called myShell

First of all we will need to make this file we can just start off by typing the following:

sudo nano myShell

Notice we didn't put the .sh extension? That's because when we run it from the terminal we will only need to type myShell in order to run our command!

Now, in nano the top line MUST be #!/bin/bash then you may leave a new line before continuing.

For demonstration I will add a basic Hello World! response

So, I type the following:

echo Hello World!

After that my example should look like this:

#!/bin/bash
echo Hello World!

Now save the file and then run this command:

chmod +x myShell

Now we have made the file executable we can move it to /usr/bin/ by using the following command:

sudo cp myShell /usr/bin/

Congrats! Our command is now done! In the terminal we can type myShell and it should say Hello World!


Add . (current directory) to your PATH variable.
You can do this by editing your .profile file.
put following line in your .profile file
PATH=$PATH:.

Just make sure to add Shebang (#!/bin/bash) line at the starting of your script and make the script executable(using chmod +x <File Name>).


Examples related to bash

Comparing a variable with a string python not working when redirecting from bash script Zipping a file in bash fails How do I prevent Conda from activating the base environment by default? Get first line of a shell command's output Fixing a systemd service 203/EXEC failure (no such file or directory) /bin/sh: apt-get: not found VSCode Change Default Terminal Run bash command on jenkins pipeline How to check if the docker engine and a docker container are running? How to switch Python versions in Terminal?

Examples related to shell

Comparing a variable with a string python not working when redirecting from bash script Get first line of a shell command's output How to run shell script file using nodejs? Run bash command on jenkins pipeline Way to create multiline comments in Bash? How to do multiline shell script in Ansible How to check if a file exists in a shell script How to check if an environment variable exists and get its value? Curl to return http status code along with the response docker entrypoint running bash script gets "permission denied"

Examples related to alias

How to open google chrome from terminal? Aliases in Windows command prompt SQL alias for SELECT statement How do I run a shell script without using "sh" or "bash" commands? Is the 'as' keyword required in Oracle to define an alias? Make a Bash alias that takes a parameter? List Git aliases How to write UPDATE SQL with Table alias in SQL Server 2008? Should I use alias or alias_method? SQL - using alias in Group By

Examples related to sh

How to run a cron job inside a docker container? I just assigned a variable, but echo $variable shows something else How to run .sh on Windows Command Prompt? Shell Script: How to write a string to file and to stdout on console? How to cat <<EOF >> a file containing code? Assigning the output of a command to a variable What does set -e mean in a bash script? Get specific line from text file using just shell script Printing PDFs from Windows Command Line Ubuntu says "bash: ./program Permission denied"