1

I need to change the directory inside the shellscript.i have tried below

#!/bin/bash
sudo -u rv bash
cd /opt/test
source /opt/rv/van.env
./rv.sh |grep "STATUS" 

When I tried it didn't cd to that path and not executed th rv.sh.guide me with some ideas.

Fyi rv.sh path /opt/test/

9
  • Add set -x as the 2nd line in the script and rerun for debug output. and paste your code in ShellCheck to solve 99% of the issues. Why not just run /opt/test/rv.sh | grep "STATUS" and avoid the directory change? Apr 8, 2020 at 18:15
  • Sudo was a typo mistake.
    – indra
    Apr 8, 2020 at 18:17
  • Does user rv have execute permission in /opt/test for file rv.sh? Apr 8, 2020 at 18:19
  • Yes it have execute permission.
    – indra
    Apr 8, 2020 at 18:20
  • What is the result of adding set -x as the 2nd line of the script? Apr 8, 2020 at 18:22

2 Answers 2

2

The following line:

sudo -u rv bash

Will launch a bash console as the user rv and then your entire script will halt until the program (i.e.: bash) ends.

Only after bash ends, the program will continue execution and run the last two lines.

The last two lines are running as part of the first script, therefor, they run as your user.

0

It seems like you're expecting sudo to execute the rest of the script in the users context but it is not interactive. It will invoke a separate bash instance and, once exited, resume the rest of the script afterwards.

You'll have to put together a separate script and run that with sudo. Running sudo inside of scripts is rarely a good idea. S.a. https://askubuntu.com/questions/425754/how-do-i-run-a-sudo-command-inside-a-script

7
  • Or use sudo -u rv bash -c ' rest in single quotes ' Apr 8, 2020 at 18:24
  • @Juan Ramierz the two lines should need to run under rv user .and should need to execute output
    – indra
    Apr 8, 2020 at 18:30
  • @David if I give your command will it change the directory also?
    – indra
    Apr 8, 2020 at 18:32
  • If you really want to change the directory for the invoking user - which might not be what they expect -, then you'll have to do that before invoking sudo. Apr 8, 2020 at 18:38
  • @milinger but I need some exact way to fire that script .
    – indra
    Apr 8, 2020 at 18:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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