Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run bash script as source without source command

Tags:

Is there any way to mark a script to be "run as source" so you don't have to add the source or "." command to it every time? i.e., if I write a script called "sup", I'd like to call it as

sup Argument 

rather than

source sup Argument 

or

. sup Argument 

Basically, I'm trying to use cd within a script.

like image 340
typeoneerror Avatar asked Apr 15 '09 16:04

typeoneerror


People also ask

Can you source in a bash script?

The source Command The built-in bash source command reads and executes the content of a file. If the sourced file is a bash script, the overall effect comes down to running it. We may use this command either in a terminal or inside a bash script.

How do I run a source in Bash?

Type the command "help source" in your shell. You will get output like this: source: source filename [arguments] Execute commands from a file in the current shell. Read and execute commands from FILENAME in the current shell.

What is the difference between executing a bash script vs sourcing it?

Sourcing a script will run the commands in the current shell process. Changes to the environment take effect in the current shell. Executing a script will run the commands in a new shell process.


2 Answers

Bash forks and starts a subshell way before it or your kernel even considers what it's supposed to do in there. It's not something you can "undo". So no, it's impossible.

Thankfully.

Look into bash functions instead:

sup() {     ... } 

Put that in your ~/.bashrc.

like image 130
lhunath Avatar answered Sep 29 '22 22:09

lhunath


When you are running a shell, there are two ways to invoke a shell script:

  • Executing a script spawns a new process inside which the script is running. This is done by typing the script name, if it is made executable and starts with a

    #!/bin/bash
    line, or directly invoking
    /bin/bash mycmd.sh
  • Sourcing a script runs it inside its parent shell (i.e. the one you are typing commands into). This is done by typing

    source mycmd.sh
    or
    . mycmd.sh

So the cd inside a shell script that isn't sourced is never going to propagate to its parent shell, as this would violate process isolation.

If the cd is all you are interested about, you can get rid of the script by using cd "shortcuts"... Take a look into the bash doc, at the CDPATH env var.

Otherwise, you can use an alias to be able to type a single command, instead of source or .:

alias mycmd="source mycmd.sh" 
like image 32
Varkhan Avatar answered Sep 29 '22 22:09

Varkhan