can I run 'su' in the middle of a bash script?

后端 未结 6 1826
刺人心
刺人心 2021-02-04 23:43

can I change/su user in the middle of a script?

if [ \"$user\" == \"\" ]; then
  echo \"Enter the table name\";
  read user
fi

gunzip *
chown postgres *
su pos         


        
6条回答
  •  故里飘歌
    2021-02-05 00:13

    Another interesting idea that I heard today is to do a recursive call on the script, when you run as root and you want to run the script as another user. See the example below:

    I am running script "my_script" as "root" and want the script to run as user "raamee"


    #!/bin/bash
    
    #Script name is: my_script
    
    user=`whoami`
    
    if [ "$user" == "root" ]; then
      # As suggested by glenn jackman. Since I don't have anything to run once 
      # switching the user, I can modify the next line to: 
      # exec sudo -u raamee my_script and reuse the same process
      sudo -u raamee my_script
    fi
    
    if [ "$user" == "raamee" ]; then
      #put here the commands you want to perform
      do_command_1
      do_command_2
      do_command_3
    fi
    

提交回复
热议问题