'Alias bash one line script

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?



Solution 1:[1]

You have several options (and I'm repeating the script from the question, not fixing any other errors (?) like redirecting to a file with name 2):

  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"
    

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1