I have a network namespace and I want to run command with this netns bash pid, how can I do it in bash script? Code example:

sudo ip netns add ns1 #this is my network namespace

#In separate shell I have to run following commands
sudo ip netns exec ns1 bash
echo $BASHPID #I want to use this bash pid in the next command 

sudo iw phy phy0 set netns xxxx # xxxx is the example of bash pid

Is it possible to run this in one bash script? When I try to do it by using command to open another shell and save bash pid as a variable it doesn't work.

  • What about using the output from ip netns pids ns1? Apr 1, 2022 at 13:32
  • I don't want to get processes id from netns ns1. I want to use ns1 $BASHPID in the command showed above in my script.
    – Spams
    Apr 1, 2022 at 13:38
  • It's the same thing as far as my tests show Apr 1, 2022 at 13:52
  • But when I execute this command bash returns nothing.
    – Spams
    Apr 1, 2022 at 13:57
  • The command sudo ip netns exec ns1 bash waits for bash to complete. It won't complete until you Ctrl/D or exit from the session it creates Apr 1, 2022 at 15:23

1 Answer 1


I am not sure if I fully understood your question, however, I'll do my best, hope it helps.

  1. Why do not you use $BASHPID instead of xxx in your code :

    sudo iw phy phy0 set netns "$BASHPID"
  2. You can store it to a variable:


    And then use the variable same as what I mentioned in number 1:

    sudo iw phy phy0 set netns "$YourVariable"
  3. You can store it to a file:

    echo "$BASHPID" > YourFile

    It creates a new file named YourFile, with the bash pid within.

    You can later on read it and use it for a new variable :

    YourVariable=$(cat YourFile)

    Note that you should be in the same directory as YourFile or use the full directory of YourFile.

    Finally, you can use YourVariable similarly as mentioned in number 2.

    sudo iw phy phy0 set netns "$YourVariable"

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .