You have defined a function random-string()
to generate random passwords containing A-Za-z0-9
and outputting only the topmost one (head -1
), from your question it is not clear that do you want to save the passwords generated after one run each time to a file or you want to do this recursively.
Let me simplify your command first :
tr -dc '[:alnum:]' </dev/urandom | fold -w 8 | head -n 1
tr
takes the character class [:alnum]
which denotes characters A-Za-z0-9
There is no need for cat
, pass the filename via STDIN to tr
Parameter expansion fold -w ${1:-8}
is not needed, just use fold -w 8
Now to save the output after one run of the function (only one password), this will overwrite the file every time, use the shell >
redirection operator :
$ random_string () { tr -dc '[:alnum:]' </dev/urandom | fold -w 8 | head -n 1 ;} >foobar
$ random_string
$ cat foobar
MqJdehaO
We are saving the STDOUT of the function random_string
to the file foobar
in the current directory.
In the next run the file will be overwritten with the new content :
$ random_string
$ cat foobar
NP85OmWw
To overwrite the file e.g. spamegg
use >>
redirection which means the STDOUT of the function will be appended to the file every time we run it :
$ random_string () { tr -dc '[:alnum:]' </dev/urandom | fold -w 8 | head -n 1 ;} >>spamegg
$ random_string
$ cat spamegg
vjwOe6TB
$ random_string
$ cat spamegg
vjwOe6TB
TBkv6qPh
To make it more flexible we can define how many passwords we want to save in one run by providing the number via number as the first argument to the function :
$ random_string () { tr -dc '[:alnum:]' </dev/urandom | fold -w 8 | head -n "$1" ;} >foobar
$ random_string 5
$ cat foobar
AV79dZeC
byitWYfX
eDBAldiI
6OxNU78H
gRs7SwEO
As you can see 5 passwords have been generated and saved in the file foobar
, change 5
with whatever number of passwords you want.
> file.txt
at the end.1>>
;)