Linux run script in directory

how to execute a shell script from any directory

I wrote a simple script with the extension .sh in my home directory that I can just run right in my home directory, but I want to run the script from every directory that I am in. What should I do?

1 Answer 1

Interactively, you can always run your scripts by typing ~/yourscript.sh on the command line, but that’s very limiting, especially if you want to write more scripts that call the scripts you’ve already written.

A more integrated and flexible approach involves putting all your scripts into one directory and adding that directory to your PATH environment variable.

After you do that, you’ll be able to type yourscript.sh , and no matter which directory you’re in, the shell will find your script and execute it.

This is how it’s usually done:

  1. Make a bin directory under your home directory and mv your scripts into it.
  2. Change all the scripts to executable ( chmod +x ).
  3. Ensure that your PATH environment variable contains your $HOME/bin directory. On some systems, the default ~/.profile will add your $HOME/bin directory to the PATH automatically, so check your ~/.profile before modifying.

Let me illustrate with some script:

mkdir ~/bin mv ~/*.sh ~/bin chmod +x ~/bin/* if ! grep 'PATH=.*HOME/bin' ~/.profile then echo 'export PATH="$HOME/bin:$PATH"' >> ~/.profile fi . ~/.profile echo "$PATH" # you should see your bin directory cd /tmp # change to another random directory type myscript.sh # see if the shell finds your scripts 

If you see your bin directory in your PATH , then it’s a good idea to logout and log back in and change to another directory and execute type yourscript.sh again to make sure everything is setup correctly.

Источник

How to run a .sh-script from any path in a terminal?

I know how to run the script I created. But it is a matter of pain that I need to change directory through terminal and run my scripts. I need to run the slowloris script, that has into Desktop, now change directory to Desktop and run. Then I have another in root; now change the directory to root and run that. My question is: How can I run any shell-script by just typing ./script from any path like we start Metasploit from any path by giving msfconsole from any path.

The easiest way is to choose a directory to hold your scripts (or softlinks to your scripts) and make sure that is in your path. On Linux, a logical choice is /usr/local/bin . Then simply make sure your scripts are executable (e.g. chmod +x ). (when choosing a scriptname it is advisable to check if any other program already uses the name with which scriptname or type scriptname ) With the script location in your path, and it being executable, you can then simply run it from anywhere by typing scriptname

Читайте также:  Linux работа оперативной памяти

Shell scripts are «shell scripts», not «.sh scripts», and don’t need to have file extensions. Bash scripts, in particular, should not use .sh extensions, as this extension implies that a script could be run with sh scriptname.sh , whereas any script with bash extensions is not guaranteed to run that way.

Typing ./script from anywhere will never run a script that is anywhere other than your current directory (a.k.a. ./ ). Even if there’s something called script somewhere in your PATH , invoking ./script will tell the shell «don’t look in $PATH, I want to run the one that is right here», with the obvious consequence if there is not, in fact, such a script.

2 Answers 2

One option is simply to type the path to the script:

This works fine, but gets a bit unwieldy.

This is what the PATH environment variable is for. And it is what $HOME/bin is for.

  1. Create yourself a directory $HOME/bin . Put all your executable scripts in it (make them executable with chmod +x script if need be †† ). This way, there’s one place to look for the scripts you want to run.
  2. Add $HOME/bin to your PATH . I put mine at the front: PATH https://stackoverflow.com/users/874188/tripleee»>tripleeenoted, once the command is installed in a directory on PATH , you no longer type ./script , but just script . This is exactly like you type ls and not /bin/ls , etc. Once the program is installed in a directory on your PATH , it is (for many purposes) indistinguishable from a system-provided command. I have about 500 scripts and programs in my $HOME/bin directory. Note that this doesn’t require any special privileges. If you have administrator access to your machine and you think other users might find your commands useful, then you could install the scripts/programs in one of the system-provided directories on your PATH . However, it is usually best not to add programs to any of:
    • /bin
    • /usr/bin
    • /sbin
    • /usr/sbin

There is often/usually /usr/local/bin which is a suitable place for widely used commands not provided by the system.

†† It would be better to use chmod a+x,go-w script ; your scripts should not be writable by other people. You could even simply use chmod 555 script or chmod 755 script . I tend to keep my scripts non-writable. That way, I have to go through a formal change process with the version control system. It means there’s less danger of uncontrolled changes.

Источник

Quick bash script to run a script in a specified folder?

I am attempting to write a bash script that changes directory and then runs an existing script in the new working directory. This is what I have so far:

#!/bin/bash cd /path/to/a/folder ./scriptname 

scriptname is an executable file that exists in /path/to/a/folder — and (needless to say), I do have permission to run that script. However, when I run this mind numbingly simple script (above), I get the response: scriptname: No such file or directory What am I missing?! the commands work as expected when entered at the CLI, so I am at a loss to explain the error message. How do I fix this?

Hmm, judging by the many (varied) responses — including one or two that must surely be overkill — I can’t help but wonder — surely there must be a simple way of chaging into a folder and running a script in that folder?

You have not copied the script to that folder. ./scriptname means the script is in that folder, which is not the case. Invoke the script by giving the correct path.

4 Answers 4

Looking at your script makes me think that the script you want to launch a script which is locate in the initial directory. Since you change you directory before executing it won’t work.

I suggest the following modified script:

#!/bin/bash SCRIPT_DIR=$PWD cd /path/to/a/folder $SCRIPT_DIR/scriptname 

No, you must have misunderstood me. I want to run scripts in /path/to/a/folder (thats why I ‘cd /path/to/a/folder’ first).

Ok I understand. I suppose everything is ok when you run it by hand. My only suggestion so far would be to add the -xv options to you #! line and check what’s printed.

cd /path/to/a/folder pwd ls ./scriptname 

which’ll show you what it thinks it’s doing.

I am already doing that (granted I did not show that in my OP — to keep things simple). pwd indicates that the cd worked and ls shows that the file is there — hence my bewilderment at the error message I am getting

I’ll accept this is as the closest answer. I was using auto competion at the CLI — so I did not enter the .sh extension. Whereas, in the script, I have to use the full file name

I usually have something like this in my useful script directory:

#!/bin/bash # Provide usage information if not arguments were supplied if [[ "$#" -le 0 ]]; then echo "Usage: $0 [. ]" >&2 exit 1 fi # Get the executable by removing the last slash and anything before it X="$" # Get the directory by removing the executable name D="$" # Check if the directory exists if [[ -d "$D" ]]; then # If it does, cd into it cd "$D" else if [[ "$D" ]]; then # Complain if a directory was specified, but does not exist echo "Directory '$D' does not exist" >&2 exit 1 fi fi # Check if the executable is, well, executable if [[ -x "$X" ]]; then # Run the executable in its directory with the supplied arguments exec ./"$X" "$" else # Complain if the executable is not a valid echo "Executable '$X' does not exist in '$D'" >&2 exit 1 fi 
$ cdexec Usage: /home/archon/bin/cdexec [. ] $ cdexec /bin/ls ls ls $ cdexec /bin/xxx/ls ls Directory '/bin/xxx/' does not exist $ cdexec /ls ls Executable 'ls' does not exist in '/' 

Источник

Run all shell scripts in folder

I have many .sh scripts in a single folder and would like to run them one after another. A single script can be executed as:

bash wget-some_long_number.sh -H 

Assume my directory is /dat/dat1/files How can I run bash wget-some_long_number.sh -H one after another? I understand something in these lines should work: for i in *.sh;. do . ; done

just put the command after do , your loop variable will be the filename without extension. Obviously, this will be missing any kind of error handling. What happens if one of the scripts fail?

3 Answers 3

for f in *.sh; do bash "$f" done 

If you want to stop the whole execution when a script fails:

for f in *.sh; do bash "$f" || break # execute successfully or break # Or more explicitly: if this execution fails, then stop the `for`: # if ! bash "$f"; then break; fi done 

It you want to run, e.g., x1.sh , x2.sh , . x10.sh :

for i in `seq 1 10`; do bash "x$i.sh" done 

To preserve exit code of failed script (responding to @VespaQQ):

#!/bin/bash set -e for f in *.sh; do bash "$f" done 

@Kirril can you explain what the break does? I do not want the job to stop at any time. Skip any failed script and continue to the next.

why -H ? ..to «Enable ! style history substitution» from man bash , or is it a conditional not listed in man bash?

@alchemy This is an option not of bash but rather of the command used in the original question ( wget-some_long_number.sh -H ).

There is a much simpler way, you can use the run-parts command which will execute all scripts in the folder:

It won’t execute all scripts. From man run-parts on Debian: . the names must consist entirely of ASCII upper- and lower-case letters, ASCII digits, ASCII underscores, and ASCII minus-hyphens (note that .sh or . is not allowed), Other files and directories are silently ignored . run-parts is primarily used by cron and is not reliable for manual usage.

run-parts was designed for a specific purpose; if you are trying to use it for something sufficiently different, it will not be a very good solution. And of course if you are not on a Debian-based platform, this particular tool doesn’t exist there. printf ‘%s\n’ ./* | sh does much the same thing anyway.

I ran into this problem where I couldn’t use loops and run-parts works with cron.

Answer:

foo () < bash -H $1 #echo $1 #cat $1 >cd /dat/dat1/files #change directory export -f foo #export foo parallel foo . *.sh #equivalent to putting a & in between each script 

You use GNU parallel, this executes everything in the directory, with the added buff of it happening at a lot faster rate. Not to mention it isn’t just with script execution, you could put any command in the function and it’ll work.

Источник

Оцените статью
Adblock
detector