Assigning the output of one command to a variable (shell)
ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
Assigning the output of one command to a variable (shell)
Hey,
I want to assign the output of one comman into a variable to be used in another command.
for example
for each i in `cat /etc/passwd`
do
#the bit that don't work
name= echo $i | ut -f1 -d :
done
I'll hazard a guess here. If I wanted to extract the full name field, that is field #5 from each line of /etc/passwd, I would pipe the output of your cat command to awk and ask it to print out only field #5 of each line like this:
cat /etc/passwd | gawk -F: '{print $5}'
Notes:
1. gawk is 'gnu awk'. It will process each line coming in from cat.
2. -F: tells gawk to treat the colon as the input field separator. (The default is a space, so we have to make that explicit).
3. '{print $5}' is the action we want to carry out. If you wanted to print out the first field then change $5 to $1.
4. Once you've extracted the field data you're interested in you can pipe it off to another process or assign it to a shell variable if you like.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.