Run Bash Commands from Txt File

Run bash commands from txt file

Just do bash file:

$ cat file 
date
echo '12*12' | bc

$ bash file
Mon Nov 26 15:34:00 GMT 2012
144

In case of aliases just run bash -i file

No need to worry about file extensions or execution rights.

Run text file as commands in Bash

you can make a shell script with those commands, and then chmod +x <scriptname.sh>, and then just run it by

./scriptname.sh

Its very simple to write a bash script

Mockup sh file:

#!/bin/sh
sudo command1
sudo command2
.
.
.
sudo commandn

How to execute commands read from the txt file using shell?

A file with one valid command per line is itself a shell script. Just use the . command to execute it in the current shell.

$ echo "pwd" > temp.txt
$ echo "ls" >> temp.txt
$ . temp.txt

I want to write a shell script that takes commands given in a .txt file and execute them

If your input file contains a list of commands you can just pipe it to bash or your favorite shell in order to execute them. You can also (better way of doing) redirect the file as stdin of bash or your favorite shell.

INPUT:

$ more commands.txt 
echo abc
echo 123

OUTPUT:

$ cat commands.txt | bash
abc
123

or even better

$ bash < commands.txt
abc
123

or simply

$ bash commands.txt
abc
123

or the best (add a shebang at the first line of your commands.txt to point to your favorite shell)

$ more commands.txt
#!/bin/bash
echo abc
echo 123

run it after giving execution permissions (chmod u+x commands.txt)

./commands.txt
abc
123

Some shebangs that might interest you:

#!/bin/sh -x
#!/bin/bash
#!/usr/bin/env bash
#!/usr/bin/perl
#!/usr/bin/env perl
#!/usr/bin/tcl
#!/bin/sed -f
#!/usr/awk -f
#!/usr/bin/python

execute a command with each list from a text file

> final.list

while IFS= read -r name; do
new_name=new_${name}.fa

cmd input-file "$name" > "$new_name"
printf '%s\t\n' "$new_name" >> final.list
done < list_of_text.txt
  • > final.list truncates (empties) the file before it gets appended.
  • while IFS= read -r line; ... loop is the canonical method of processing one line of an input stream at a time. It is also far more robust compared to looping over an unquoted command substitution.
  • < list_of_text.txt redirects the list as input for the while read loop.


Related Topics



Leave a reply



Submit