Home > Software engineering >  Alias bash one line script
Alias bash one line script

Time:05-16

I have to do an alias called for example "longest" for this script:

data=""; len=0; line=""; while [[ $line != "quit" ]]; do read line; [[ $line != "quit" ]] && [[ ${#line} -gt len ]] && len=${#line} data=$line; done; echo $len; echo $data 1>2

Its job is simply reading words or phrases and counting the characters.

I put the script inside quotes like this:

alias longest="...script..."

but it doesn't work and I don't know why. Can anyone explain to me why? A possible solution?

CodePudding user response:

You have several options:

  1. Have the alias define a function and execute it immediately

    alias longest='f() { data=""; len=0; line=""; while [[ $line != "quit" ]]; do read line; [[ $line != "quit" ]] && [[ ${#line} -gt len ]] && len=${#line} data=$line; done; echo $len; echo $data 1>2; }; f'
    
  2. Create a script and save it in a directory from your PATH, usually ~/bin:

    File ~/bin/longest:

    #!/bin/bash
    data="";
    len=0;
    line="";
    while [[ $line != "quit" ]]; do
       read line;
       [[ $line != "quit" ]] && [[ ${#line} -gt len ]] && len=${#line} data=$line;
    done;
    echo $len;
    echo $data 1>2
    

    and finally chmod x ~/bin/longest.

  3. Define the function in your .bashrc file and then call it on demand.

  4. Avoid the complicated, home-grown code and go for something much simpler. The behavior and output will not be identical, but should be sufficient.

    alias longest="awk '{print length, $0}' | sort -nr | head -1"
    

CodePudding user response:

alias longest='
len=0
while read -p "input: " line
do
  [ "$line" != "quit" ] && {
     [ ${#line} -gt $len ] && {
        len=${#line}
        data="$line"
     }
  } || break
done
echo "data=$data"
echo len=$len
'

$ longest
input: foo bar
input: quit
data=foo bar
len=7
  • Related