1

I want to assign a part of my current working directory path name to a variable and use it in a script inside the directory itself.

For eg:

If my pwd is :

/home/desktop/project/ABC/abc/abc_123, is there a command to assign ABC to a variable, say $PROJECT_NAME?

I tried dirname, but it seems to be returning '.' for input 'pwd', and anyway I need one more step behind than what dirname can supposedly return.

  • have you tried using $PWD variable? – Rakesh.N Mar 6 '17 at 12:03
  • @Rakesh.N Yeah, in fact I did a second after I posted. But even that gives ' /home/desktop/project/ABC/abc/' whereas I'm looking for 'ABC' – Ambareesh S J Mar 6 '17 at 12:07
  • 1
    try this: var=$(echo $PWD|awk -F'/' '{print $5}') – Rakesh.N Mar 6 '17 at 12:13
  • Giving me "Illegal variable name" error – Ambareesh S J Mar 6 '17 at 12:23
2

Since you're tagging with tcsh:

set project = $cwd:h:h:t:q

Would set $project to the tail of the head of the head of the current directory (or basename of the dirname of the dirname). :q quotes the resulting text so no further expansions (like splitting or globbing) are done on it.

pwd is the command to print the current working directory. That command is not built-in tcsh. The current working directory is (unsurprisingly, or at least less surprisingly that with ksh's $PWD) in the $cwd variable in tcsh.

  • Worked like a charm. What does the :q part add to it though? – Ambareesh S J Mar 6 '17 at 12:42
  • @AmbareeshSJ see edit. The need to use that :q on all variable expansions, and the fact that there's no equivalent for command substitution are one of the many reasons using (t)csh is not recommended. – Stéphane Chazelas Mar 6 '17 at 12:50
  • Oh alright. But I tried it without the :q and it seemed to work just fine, hence the doubt. TY! – Ambareesh S J Mar 6 '17 at 12:54
  • @AmbareeshSJ, try after mkdir -p '*/a/b'; cd '*/a/b' for instance. – Stéphane Chazelas Mar 6 '17 at 12:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.