What is the difference between “./somescript.sh” a

2019-01-12 03:53发布

问题:

Today I was following some instructions to install a software in Linux. There was a script that needs to be run first. It sets some environment variables.

The instruction told me to execute . ./setup.sh, but I made a mistake by executing ./setup.sh. So the env was not set. Finally I noticed this and proceeded.

I want to know the difference between these two methods of invoking a script. I am completely new to Linux so please be as elaborate as possible.

回答1:

./setup.sh runs the script, a new shell will be started that runs the script. That new shell cannot affect the parent shell that started the script.

. ./setup.sh is a shorthand for source ./setup.sh and it will run the script in the current shell, instead of starting a new shell to run it. This means the script can alter the behavior of the current shell, e.g. set new environment variables.



回答2:

Edit: I just realized I didn't answer the other part of your question .. but the answer by leeroy does that. I kind of answered something else, but I hope it helps :-)

The sh function runs bash on the script you present it with. See the man page for more info, but you can see sh is basically the synonym for bash

When you run a script ala ./setup.sh it identifies the script based on what is at the top of the file, normally referred to as the "Shebang"

A bash script would have

#!/bin/sh

Or similar at the top of the file, allowing you to use the dot method. You can also use other things, like a Python script can have

#!/usr/bin/env/python

And if your path is correct, it would run the script as a Python script instead of a bash one using the dot notation.

Hope that explains it in a simple manner!



回答3:

Just run "source /path/to/setup.sh"

This will set up environment variables in current shell.



回答4:

. refers to the current directory. So ./script.sh means run the script in the current directory.

../script.sh would run script.sh in the parent directory.

. ./script.sh (with a space between the dots) would complain in some shells like csh but in bash . foo is shorthand for source foo.



标签: linux shell