Re: bash cut problem?



On 2009-09-23, pk wrote:
T wrote:

Hi:

I'm having trouble when piping a variable to the "cut" command:

bash-3.2$ foo=`ssh cc1 date '+%Y%m%d%H%M%S'`
bash-3.2$ echo $foo
20090923151350
bash-3.2$ echo -n $foo | cut -c1

bash-3.2$

First thing to do is to quote the variable, and not use -n:

echo "$foo" | cut -c1

If you want to get the first character, in bash you can also do

echo "${foo:0:1}"

In any POSIX shell:

printf "%s\n" "${foo%"${foo#?}"}"

In bash:

read -n1 fc <<.
$foo
..
printf "%s\n" "$fc"


--
Chris F.A. Johnson, author <http://cfaj.freeshell.org/shell/>
Shell Scripting Recipes: A Problem-Solution Approach (2005, Apress)
===== My code in this post, if any, assumes the POSIX locale
===== and is released under the GNU General Public Licence
.



Relevant Pages

  • Re: Environment bug in Bash?
    ... Thinking it might be because echo is ... I tried in in bash, ksh, and zsh, all with the same ... env foo=bar echo $foo ... So, yes, I think you hit a bug in bash 2.x 3.x! ...
    (comp.unix.shell)
  • Re: Environment bug in Bash?
    ... Thinking it might be because echo is ... I tried in in bash, ksh, and zsh, all with the same ... env foo=bar echo $foo ... So, yes, I think you hit a bug in bash 2.x 3.x! ...
    (comp.unix.shell)
  • Re: Environment bug in Bash?
    ... Thinking it might be because echo is ... I tried in in bash, ksh, and zsh, all with the same ... env foo=bar echo $foo ...
    (comp.unix.shell)
  • Re: Environment bug in Bash?
    ... Thinking it might be because echo is ... I tried in in bash, ksh, and zsh, all with the same ... env foo=bar echo $foo ... and redirections, ...
    (comp.unix.shell)
  • Re: Bash bug?
    ... function foo() { ... echo Foo | while read x ... the right-hand-side of the pipe runs in a subshell. ... When the 2nd process finished, your commandline shell reaped it's status, ...
    (comp.unix.shell)