MsA
MsA

Reputation: 2979

Using bash script with awk as command

I was learning awk from here.

There it gives:

column.sh

#!/bin/sh
column="$1"
awk '{print '"$column"'}'

But then doing following gave me error:

$ ls -l | column 3 
column: 3: No such file or directory

How can use column.sh as command?

Upvotes: 0

Views: 102

Answers (1)

KamilCuk
KamilCuk

Reputation: 140900

Question: How can use column.sh as command?


Use column.sh as a command. Obviously, column is not column.sh.

So you may:

/the/directory/with/the/script/column.sh 3
# or
cd /the/directory/with/the/script
./column.sh 3

Alternatively, you may add the path to the script to PATH environment variable. Or you may add the script to one of the paths already existing in PATH.

export PATH="$PATH:/the/directory/with/the/script"
column.sh 3

User scripts are typically installed in $HOME/bin or, you may follow the extension to xdg-user-dirs specification, use $HOME/.local/bin directory or for all users in /usr/local/bin.


Note: an update of your script should read:

#!/usr/bin/env bash
[[ "$1" =~ [^0-9] ]] || exit 1
awk -v c="$1" '{print $c}'

Upvotes: 4

Related Questions