'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):
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'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>2and finally
chmod +x ~/bin/longest.Define the function in your
.bashrcfile and then call it on demand.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 |
