How to run a shell script on a Unix console or Mac terminal?

前端 未结 7 990
执念已碎
执念已碎 2020-11-28 16:54

I know it, forget it and relearn it again. Time to write it down.

相关标签:
7条回答
  • 2020-11-28 17:26

    First, give permission for execution:-
    chmod +x script_name

    1. If script is not executable:-
      For running sh script file:-
      sh script_name
      For running bash script file:-
      bash script_name
    2. If script is executable:-
      ./script_name

    NOTE:-you can check if the file is executable or not by using 'ls -a'

    0 讨论(0)
  • 2020-11-28 17:34

    For the bourne shell:

    sh myscript.sh
    

    For bash:

    bash myscript.sh
    
    0 讨论(0)
  • 2020-11-28 17:34

    If you want the script to run in the current shell (e.g. you want it to be able to affect your directory or environment) you should say:

    . /path/to/script.sh
    

    or

    source /path/to/script.sh
    

    Note that /path/to/script.sh can be relative, for instance . bin/script.sh runs the script.sh in the bin directory under the current directory.

    0 讨论(0)
  • 2020-11-28 17:35

    Little addition, to run an interpreter from the same folder, still using #!hashbang in scripts.

    As example a php7.2 executable copied from /usr/bin is in a folder along a hello script.

    #!./php7.2
    <?php
    
    echo "Hello!"; 
    

    To run it:

    ./hello
    

    Which behave just as equal as:

    ./php7.2 hello
    

    The proper solutions with good documentation can be the tools linuxdeploy and/or appimage, this is using this method under the hood.

    0 讨论(0)
  • 2020-11-28 17:36

    The file extension .command is assigned to Terminal.app. Double-clicking on any .command file will execute it.

    0 讨论(0)
  • 2020-11-28 17:45

    To start the shell-script 'file.sh':

    sh file.sh
    
    bash file.sh
    

    Another option is set executable permission using chmod command:

    chmod +x file.sh
    

    Now run .sh file as follows:

    ./file.sh
    
    0 讨论(0)
提交回复
热议问题