DWQA QuestionsCategory: ServerHow does bash get the absolute path of the script?
Sulfonamide asked 1 month ago

At present, the method adopted by the subject is as follows (absolute path, excluding all soft links)

#!/bin/bash

SCRIPT_PATH=`cd "$(dirname "$0")"; pwd -P`
echo ${SCRIPT_PATH}
cd ${SCRIPT_PATH}

This method has the following problems:

  1. Path cannot contain non askii characters (for example: Chinese)
  2. Path cannot contain bash special characters (for example: $, \)
  3. Path cannot contain white space (e.g. spaces, tabs)

Please provide a way to avoid the above problems.
Test method:

  • The following script will be modified and put here:Your path / Chinese English $/ Chinese English $. Sh。 There is no error in execution.
  • It is better to test on windows (Windows subsystem for Linux), MacOS and Linux.
#!/bin/bash

#Modify here
#
# SCRIPT_PATH=
echo ${SCRIPT_PATH}
cd ${SCRIPT_PATH}

PS: Yescd ${SCRIPT_PATH}The reason for testing is to ensure that${SCRIPT_PATH}Can be safely used as a parameter for arbitrary commands and scripts.

3 Answers
Yujiaao answered 1 month ago

Try this, not on windows

#! /bin/sh
echo "$(cd "$(dirname "$1")"; pwd -P)/$(basename "$1")"
Sulfonamide replied 1 month ago

code:
SCRIPT_PATH="$(cd "$(dirname "$1")"; pwd -P)/$(basename "$1")"
echo ${SCRIPT_PATH}
cd ${SCRIPT_PATH}

function:
$. / Chinese
/Users / ZZC / desktop / Chinese English$/
. English $. Sh: Line 3: CD: users / ZZC / desktop / Chinese: no such file or directory

The results were not as expected.
PS: Yescd ${SCRIPT_PATH}The reason for testing is to ensure that${SCRIPT_PATH}Can be safely used as a parameter for arbitrary commands and scripts.

Yujiaao replied 1 month ago

The variable after CD needs to be enclosed in quotation marks

Sulfonamide replied 1 month ago

I see. You’re telling me.
Use double quotation marks (“) where you need to use them as command parameters.
#!/bin/bash

SCRIPT_PATH=`cd "$(dirname "$0")"; pwd -P`
echo ${SCRIPT_PATH}
cd "${SCRIPT_PATH}"

Feng_Yu answered 1 month ago

userealpathit’s fine too:

SCRIPT=`realpath $0`
SCRIPTPATH=`dirname $SCRIPT`

If you don’t want to track soft links, you can add-sParameters:

SCRIPT=`realpath -s $0`
SCRIPTPATH=`dirname $SCRIPT`
Sulfonamide answered 1 month ago

@YujiaaoYour answer reminds me.
Use double quotation marks (“) where you need to use them as command parameters.

#!/bin/bash

SCRIPT_PATH=`cd "$(dirname "$0")"; pwd -P`
echo ${SCRIPT_PATH}
cd "${SCRIPT_PATH}"