How do I run a shell script without using “sh” or

2019-01-04 04:31发布

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.

8条回答
forever°为你锁心
2楼-- · 2019-01-04 05:23

These are some of the pre-requisites of using directly the script name:

  1. Add the sha-bang {#!/bin/bash) line at the very top.
  2. Using chmod u+x scriptname make the script executable.
  3. Place the script under /usr/local/bin folder.
  4. Run the script using just the name of the script.

Note: The reason I suggested to place it under /usr/local/bin folder is because most likely that will be path already added to your PATH variable.

Update:

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

  1. Create a folder in your home directory and let's call it myscripts.
  2. Do ls -lart on your home directory, to identify the start-up script your shell is using. It should either be .profile or .bashrc.
  3. Once you have identified the start up script, add the following line in your script - export set PATH=$PATH:~/myscript.
  4. Once added, source your start-up script or log out and log back in.
  5. Execute your script using script name.
查看更多
做个烂人
3楼-- · 2019-01-04 05:25

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)

查看更多
登录 后发表回答