i am trying to change dir when from A path to B path like below

pwd|awk '{if($1=="/") cd /tmp/}'
awk: syntax error near line 1
awk: illegal statement near line 1

please suggest


Calling cd from within awk is possible (using system(), there is no awk command that is called cd), but wouldn't do much. In particular, it would not change the current working directory of the shell that started awk. The working directory is local to an environment, and awk and any other process or subshell are running in their own environments, inherited from their parent processes (and the parent process' environment can't be changed from a child process).

If you just want to see whether the current directory is the root directory and cd to /tmp if it is, then you may do so in the shell directly:

[ "$PWD" = "/" ] && cd /tmp
  • Strictly speaking the OP's code would also attempt to cd /tmp when $PWD is "/ dir with spaces/there" or $'/tmp/a\n/\n/b'... – Stéphane Chazelas Sep 11 '18 at 11:57
  • @StéphaneChazelas Yes, due to the way awk would split the line. I don't think that was the intention though. – Kusalananda Sep 11 '18 at 11:58

You can use system() in awk to run any command, but you cannot use it to change directory as it runs the command in a subshell, so that you will change directory in the subshell which will immediately exit. The command would be as follows:

pwd|awk '$0 == "/"{system("cd /tmp")}'

But as I said it will not work. If you add echo in front of the command you can see it is in fact running when you'd expect it too:

$ cd /
$ pwd|awk '$0 == "/"{system("echo cd /tmp")}'
cd /tmp
$ cd /home
$ pwd|awk '$0 == "/"{system("echo cd /tmp")}'

I think it would be better to just use and if statement:

if [ "${PWD}" = '/' ];then 
  cd /tmp

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.