0

I was going through shell script wriiten by someone else. I could see below lines at starting of the script. i know it has to do something with path and all. But can anyone explain about it how it works?

#!/bin/ksh

scripttorun=${0}
scriptname=${0##/*/}
scriptname=$(basename $0)
scriptpath=${0%%/$scriptname}
if [ $scriptpath != $0 ];then
cd $scriptpath
fi
Gaurav Parek
  • 317
  • 6
  • 20
  • possible duplicate of [What are the special dollar sign shell variables?](http://stackoverflow.com/questions/5163144/what-are-the-special-dollar-sign-shell-variables) – devnull May 20 '14 at 11:46

2 Answers2

2

scripttorun=${0} just assigns the content of $0 into scripttorun.

You could also use instead (no need to use {...} in this case) :

scripttorun=$0

$0 is the first argument of the script that contains the invoked command (for example : ./script.sh).

Otherwise :

if [ $scriptpath != $0 ];then
cd $scriptpath
fi

You must protect your operands with double quotes when you use test or [. See this reminder to get more details.

So you could use instead :

if [[ $scriptpath != $0 ]]; then
    cd "$scriptpath"
fi

# or

if [ "$scriptpath" != "$0" ]; then
    cd "$scriptpath"
fi
Community
  • 1
  • 1
Idriss Neumann
  • 3,760
  • 2
  • 23
  • 32
0

the following line:

scripttorun=${0}

assigns the local variable $scripttorun with the argument #0 of the script. As a convention, in Unix programs, ${0}, the argument number 0, is always the calling path to the script being executed.

What this snippet does, is taking out the file name from the path to the current script, and make the current working directory the path where the script sits in.

zmo
  • 24,463
  • 4
  • 54
  • 90
  • so mean to say from anypath you execute the script it will get the path where calling script is present and then will change directory to it if it is called from somewheresel? – Gaurav Parek May 20 '14 at 11:58
  • and also what about the other variable what they are doing srciptname/ – Gaurav Parek May 20 '14 at 12:00