How may I detect the name of the directory (or better yet the entire path) in which my shell script is run?
            Asked
            
        
        
            Active
            
        
            Viewed 4.2k times
        
    4 Answers
21
            what shell? What operating system?
For starters try
man pwd
$PWD
 
    
    
        Anycorn
        
- 50,217
- 42
- 167
- 261
- 
                    And if you do want just the directory's name, instead of the full path, read man basename too. – Nov 30 '09 at 02:46
17
            
            
        This, I believe, is the most portable way:
dir=$(cd -P -- "$(dirname -- "$0")" && pwd -P)
 
    
    
        glenn jackman
        
- 238,783
- 38
- 220
- 352
3
            
            
        This is not as trivial as it looks like. Check out this question and this
- 
                    The question is about determining the script execution directory, but your answer is for determining the name / directory of the script file. – Mat Gessel Mar 12 '17 at 19:44
- 
                    
- 
                    Could you add a little bit more information? See https://meta.stackexchange.com/questions/8231/are-answers-that-just-contain-links-elsewhere-really-good-answers – Marco May 05 '18 at 23:02
0
            
            
        alternative method
pid=$$
path=$(ps -eo pid,args| awk -vp=$pid '$1~p{print $3}')
case "$path" in
    ./* ) pwd;;
    * ) echo $path;;
esac
 
    
    
        ghostdog74
        
- 327,991
- 56
- 259
- 343
 
     
    