Alex
Alex

Reputation: 21

Display the name of all running processes in Linux in a file using a bash script

I need to display the name of all running processes in Linux in a file using a bash script. I wrote the code, but didnt succeed:

#!/bin/bash
for i in `ps aux| awk '{print $5}'`; 
echo $i > /tmp/test; 
done

Need your assistance, Thanks.

Upvotes: 0

Views: 910

Answers (2)

Boba Fit
Boba Fit

Reputation: 829

I'm not sure, what your output should look like. With your template, and the fixes from Glauco Leme, I only got the VSZ of all the processes.

I assume you need the cmd of each process, then you just can use ps -e --no-headers --format cmd.

In case you need it in a file:

ps -e --no-headers --format cmd > /tmp/test

I hope this will do what you need.

Upvotes: 1

Glauco Leme
Glauco Leme

Reputation: 23

Using the for, the syntax is slightly different:

#!/bin/sh
cat /dev/null > /tmp/test
for i in $(ps aux | awk '{print $5}'); do
    echo $i >> /tmp/test;
done
  1. You missed the do operator
  2. The output redirector > on a loop should change to appending >>, otherwise only the last value of the loop will be saved.

But as @stark said, the for is not required:

#!/bin/sh
ps aux | awk '{print $5}' > /tmp/test;

Upvotes: 1

Related Questions