Question

bash: how to split a string, assign tokens to an array

Asked by: brettmjohnson

I am having difficulty splitting a colon-delimited string and assigning the
tokens to an array in a bash shell script.  I want to assign the passwd fields
returned by `id -P username` to an array.

Given that
      `id -P cyrus`
returns
      cyrus:*:77:6::0:0:Cyrus User:/var/imap:/usr/bin/false

I wish to assign the fields to an array, say pw, such that
pw[0] = cyrus
pw[1] = *
pw[2] = 77
 ...
pw[8] = Cyrus User
pw[9] = /var/imap
... etc

I already discovered that ' set -f ' avoids the '*' from getting filename-expanded.
I tried using awk to split the colon-delimited string, but the GECOS field can contain spaces,
resulting in its value getting further split during the array assignment:
   ...
pw[8] = Cyrus
pw[9] = User
   ....

I have a feeling that there is a simple solution, but I haven't found it yet.

Equally acceptable would be a 'read'- style assignment to multiple variables.
Something like
IFS=':'
read f_uname f_pass f_uid f_gid ...

But read takes intput from stdin.

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2004-07-13 at 08:34:58ID21057113
Tags

bash

,

split

,

string

Topic

Linux Programming

Participating Experts
5
Points
500
Comments
12

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. csh to bash
    how do you say this csh statement USER_REPLY = $< in bash? that's to get user input while running the script, not from command line arguments.
  2. Bash shell for root?
    Hi All, Just a quick, easy one. Are there any good reasons why you would not use the bash shell for the root account on a Solaris 8/9 box? Thanks, jnbkze
  3. bash shell
    useing solaris 9 i login and change to bash shell, what do I need to do to make my shell bash so i don't have to change to it or at least setup a profile that will take effect for bash when I change to bash. do i need to create a '.bashrc' file? right now all i have in ...
  4. ssh-agent bash
    I am using SUSE Linux Enterprise Server 9. I have come over this command "ssh-agent bash" What is the meaning by putting the "bash" after "ssh-agent"?
  5. bash problem 'unexpected token'
    I'm new to bash and I have spent 2 hours on this simple argument parsing routine. 5 algorithms lifted right out of tutorials and manuals all fail at the same place. What am I missing here? #!/usr/bin bash #parse arguments while [ $# -gt 0]; do case "$1" in ...
  6. wrong bash
    hello, My ensim web hosting control panels adds users to the server, and then I can login this way. username: user@domain.com Password: pass but im having problems because I cant execute commands -bash-2.05b$ uptime -bash: uptime: command not found -bash-2.05b$ wget http:/...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: da99rmdPosted on 2004-07-13 at 09:46:15ID: 11540748

Hi brettmjohnson,
here is a solution i have used in some scripts maybe there is a better one:
array=(`id -P cyrus | awk 'BEGIN{FS=":";OFS=",";}{print $1,$2,$3,$4,$5,$6,$7}' | sed 's/ /KALLEKOSKIT/g' | sed 's/,/ /g'`)
this will give you the string KALLEKOSKIT as a " " sign.
so when you use the string just use this command
echo `echo $array[4] | sed 's/KALLEKOSKIT/ /g'

i hoped it helped.

/Rob

 

by: da99rmdPosted on 2004-07-13 at 09:55:06ID: 11540845

Hi brettmjohnson,
what will the entire script do maybe i can bring you a better solution.
/Rob

 

by: brettmjohnsonPosted on 2004-07-13 at 10:42:02ID: 11541323

> ... awk 'BEGIN{FS=":";OFS=","; ...

Unfortunately, the GECOS field can contain commas (it is actually a comma-separated list in itself).
I have already used awk for splitting, but I was looking for a slightly more elegant solution.


> what will the entire script do maybe i can bring you a better solution.

I am writing a set of adminstration scripts for a client that has a Linux box
acting as a web server for 2 dozen virtual domains and a mail server (using Qmail)
for both local users (shell acct, POP3/SMTP) and "virtual users" (forwarding all
mail for a virtual domain to an external party).

I am using the username, UID, full name extracted from the GECOS field, and
home directory field for various administrative tasks.

 

by: glassdPosted on 2004-07-13 at 11:21:39ID: 11541766

have you considered the "cut" command:

Line=$(id -P cyrus)

for i in 1 2 3 4 5 6 7
do
   pw[$i]=$(echo "$Line" | cut -d: -f$i)
done

 

by: Jeff_2Posted on 2004-07-13 at 12:43:44ID: 11542516

> id -P cyrus

I am getting an error on SuSE 8.0...

% id --version
id (GNU sh-utils) 2.0

% id -P root
id: invalid option -- P

Just curious, what version of  "id" are you using ?

 

by: brettmjohnsonPosted on 2004-07-13 at 15:45:20ID: 11544204

> Just curious, what version of  "id" are you using ?

Excellent observation.  Although the target machine is running RH 7.1,
I was prototyping the utility on Mac OS X, which uses id v1.19 from FreeBSD.
I will probably have to change it to grep the /etc/passwd file for the appropriate fields.

I like the idea of using 'cut' to split the string, 'tho.

But I will going to give an A grade to a good solution that uses a built-in  
or external command that doesn't need to iterate (reparsing the string each time).


 

by: rjkimblePosted on 2004-07-13 at 20:52:29ID: 11545791

I found this page:

http://www.unixguide.net/unix/bash/E4.shtml

It appears that you can do something like this:

IFS=:
read f_uname f_pass f_uid f_gid f_therest <<END
$(id -P cyrus)
END
echo $f_uname
echo $f_pass
echo $f_uid
echo $f_gid
echo $f_therest

You should also be able to do something like this:

read f_uname f_pass f_uid f_gid f_therest < <(IFS=:; id -P cyrus)

I tested both approaches using "echo $PATH" as the command -- instead of "id -P cyrus" -- using bash on Mandrake 10 and they worked as advertised.

 

by: da99rmdPosted on 2004-07-14 at 02:28:44ID: 11546977

brettmjohnson,
Made a function for this purpose with the same syntax as explode in php

# Function
myexplode () {
array=`echo $2 | awk "BEGIN{FS=\"$1\";OFS=\"NISSEPISSE\";}{print \\$1,\\$2,\\$3,\\$4,\\$5,\\$6,\\$7}" | sed 's/ /KALLEKOSKIT/g' | sed 's/NISSEPISSE/ /g'`
echo $array
i=0
for ar in $array
do
   tmp[$i]=`echo "$ar" | sed 's/KALLEKOSKIT/ /g'`
   i=`expr $i + 1`
done
return $tmp
}
# End func

#test script
tmp= myexplode ":" "`tail -n 1 /etc/passwd`"
echo ${tmp[4]}
exit
# End

/Rob

 

by: NovaDenizenPosted on 2004-07-14 at 10:51:41ID: 11551658

This script does everything internally.  You might want to tweak the way it loops to more robustly handle short input strings.  I'm not sure what your restriction about iteration means.

#!/bin/bash

set -f
VAR="cyrus:*:77:6::0:0:Cyrus User:/var/imap:/usr/bin/false"

TMP=$VAR
for i in 0 1 2 3 4 5 6 7 8 9; do
    RES[$i]=${TMP%%:*}
    TMP=${TMP#*:}
done
echo res[3] is ${RES[3]}

echo "\$VAR is $VAR"
echo -n "\$RES is:"
for i in ${RES[@]} ; do
    echo -n " '$i'"
done
echo

 

by: NovaDenizenPosted on 2004-07-14 at 10:58:34ID: 11551737

My script mistakenly prints out 'Cyrus' and 'User' as two separate entries, but that is just a bug in my display loop.  ${RES[7]} correctly contains "Cyrus User".

 

by: NovaDenizenPosted on 2004-07-14 at 11:03:58ID: 11551797

To print out correctly, use this line for the second for loop:
for i in "${RES[@]}" ; do

 

by: brettmjohnsonPosted on 2004-07-14 at 11:46:20ID: 11552258

I awarded an A grade to rjkimble's read using HERE i/o redirection because:
 - it is simple and elegant
 - it uses a built-in to do the splitting
 - it doesn't iterate calling external commands

I give additional points to glassd,  for suggesting cut -d: (which I made use of elsewhere),
and Jeff_2 for pointing out that id -P won't work on my target platform (I now grep /etc/passwd).

Thank you all for your help.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...