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 ...
- 11-08-2009 #1Just 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
- 11-08-2009 #2
You can use a for loop to get each number:
Code:for ((i=0; ${1:$i:1}; i++)) do echo ${1:$i:1} doneLinux User #453176
- 11-08-2009 #3Just 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?
- 11-08-2009 #4Just 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!
- 11-08-2009 #5
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


Reply With Quote
