Bash script to execute a single command over multiple inputs one by one

I have a linux based command named as x2goterminate-session followed by username e.g

x2goterminate-session john

But there are numerous user sessions that I want to terminate in a single go.

slpusrs=`x2golistsessions_root | grep '|S|' | cut -d "|" -f 2`

Above variable slpusrs finds the list of sleeping users and stores them in the slpusrs variable.

Now I want to execute x2goterminate-session command one by one on the list of users, so that all sleeping users are terminated in a single go instead of typing the command followed by user one by one.

command=x2goterminate-session
for i in "${slpusrs[@]}"; do
"$command" "$i"
done

But It isnt working. Please help

Upvotes: 1

Views: 1427

Answers (3)

user1934428
user1934428

Reputation: 22225

If x2goterminate-session realls can work only on one user at a time, you can do a

for user in $(x2golistsessions_root | grep '|S|' | cut -d "|" -f 2)
do
  echo "Murdering unser $user ..."
  x2goterminate-session "$user"
done

No need to introduce a separate variable, unless you need the list of users later on again.

Upvotes: 0

Léa Gris
Léa Gris

Reputation: 19555

Instead of iterating with Bash, use xargs to run your command for each user.

x2golistsessions_root |
  grep '|S|' |
    cut -d "|" -f 2 |
      xargs -n1 x2goterminate-session

Upvotes: 2

Barmar
Barmar

Reputation: 780949

slpusrs is a string, not an array. Use

for i in $slpusrs; do
    "$command" $i"
done

Upvotes: 2

Related Questions