Find the answer to your Linux question:
Results 1 to 5 of 5
Hi, I have to create a bash script that takes an arbitrary length number from the command line, and add up each individual digit Ex: server> myscript.sh 123 server> 1 ...
  1. #1
    Just Joined!
    Join Date
    Nov 2009
    Posts
    3

    Parse string in bash script



    Hi,

    I have to create a bash script that takes an arbitrary length number from the command line, and add up each individual digit

    Ex:
    server> myscript.sh 123
    server> 1 + 2 + 3 = 6

    The problem I'm having is pulling out each character.

    Is there a way in bash I can parse the input string for each character? I can't figure out a way to do this.

    Thanks!

    -Max

  2. #2
    Linux Engineer Kieren's Avatar
    Join Date
    Aug 2007
    Location
    England
    Posts
    845
    You can use a for loop to get each number:

    Code:
    for ((i=0; ${1:$i:1}; i++))
    do
            echo ${1:$i:1}
    done
    Linux User #453176

  3. #3
    Just Joined!
    Join Date
    Nov 2009
    Posts
    3
    Thanks for replying!

    I tried running that, but all I get is "command not found." Do you know what might be causing it?

  4. #4
    Just Joined!
    Join Date
    Nov 2009
    Posts
    3
    Oops! Nevermind, I'm an idiot :P I had #!/bash/sh as the first line, instead of #!/bin/sh

    Thanks again for your help!

  5. #5
    Linux Engineer Kieren's Avatar
    Join Date
    Aug 2007
    Location
    England
    Posts
    845
    Sorry I'm not sure what it is you have done. If you enter that code into a text file and save it it should run. If you save it as myscript.sh you run it as:

    Code:
    ./myscript.sh 123454321
    Linux User #453176

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •