Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set the current working directory to the directory of the script in Bash?

I'm writing a Bash script. I need the current working directory to always be the directory that the script is located in.

The default behavior is that the current working directory in the script is that of the shell from which I run it, but I do not want this behavior.

like image 972
jameshfisher Avatar asked Jul 28 '10 00:07

jameshfisher


People also ask

How do I get the current script directory?

pwd can be used to find the current working directory, and dirname to find the directory of a particular file (command that was run, is $0 , so dirname $0 should give you the directory of the current script).

What is working directory in shell script?

The current working directory is the directory in which the user is currently working in. Each time you interact with your command prompt, you are working within a directory. By default, when you log into your Linux system, your current working directory is set to your home directory.

How do I change the current working directory in Linux?

To change to the current working directory's parent directory, type cd followed by a space and two periods and then press [Enter]. To change to a directory specified by a path name, type cd followed by a space and the path name (e.g., cd /usr/local/lib) and then press [Enter].


1 Answers

#!/bin/bash cd "$(dirname "$0")" 
like image 115
ndim Avatar answered Sep 22 '22 08:09

ndim