Display header in script output


 
Thread Tools Search this Thread
Top Forums UNIX for Dummies Questions & Answers Display header in script output
# 1  
Old 10-14-2013
Display header in script output

Hi -- Working on my own through the book "Learning the KornShell and came to task 4-1, which there is:
a script "highest" and it will sort an "album" file.
highest filename

The author mentions adding a header line to the scripts output if the user types in the -h option. It says "assume the option ends up in the variable "header" i.e $header is -h"

If user runs the script with -h, it will produce a header on the output that reads "Album Artist" and a new line" if the -h option is not used there is no header or new line.

From the book:
The expression
${header:+"Albums Artist\n")
yields null if the variable header is null or "Albums Artist\n" is not null.
we can put the line:
print -n ${header:+"Albums Artist\n"}

My problem is i do not know how to make $header relate to the -h option. It says "assume....." but i want to follow along and run the script. Tried the man pages, but no luck. If you have any ideas please respond. Thanks.
# 2  
Old 10-14-2013
Look into getopt.
# 3  
Old 10-14-2013
What you want to do is simple:

Code:
# pseudocode:
if [ command line options passed include "-h" ] ; then
     header="-h"
else
     header=""
fi

How you can achieve that: see CarloMs post above. getopts (probably preferable to "getopt" because being a shell builtin) is the canonical method.

I hope this helps.

bakunin
# 4  
Old 10-15-2013
Ok thanks to the both of you. I was able find a "go_test" script to use as a work around to print a header when using the -h option using the getopts. The album sort script works well. However when i try to combine them into one script, it messes up the sort -n and header options. If you have any suggestions please let me know.


vi albums
Code:
17 Rolling Stones
20 Led Zeppelin
5 ACDC
16 Aerosmith
12 Black Crowes
4 The Cult
22 Tom Petty
10 Nirvana
18 Stone Temple Pilots
8 Van Halen
1 Talking Heads

go_test -h
vi go_test
Code:
while getopts ":h" opt; do
  case $opt in
    h)
      print -n "ALBUMS ARTIST\n" >&2
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      ;;
  esac
done

highest albums [howmany]
howmany default is 10
vi highest
Code:
filename=$1
filename=${filename:?"Filename Missing, include the filename after the \"highest\" script as an arguement."}
howmany=$2
sort -nr "$filename" | head -${howmany:=10}

# 5  
Old 10-15-2013
What does your complete script look like? Also, what are your expected arguments now? It looks like you have a 'highest' parameter rather than just outputting a header.
# 6  
Old 10-15-2013
The script name is highest
The first required parameter is "filename" and the filename here is "albums". If no "filename" is provided a message is displayed.
The second parameter is an optional number [how many] meaning how many albums/artist do you want to display (default of 10).
There is also a requirement that if the user uses the -h option, it would create a header "ALBUMS ARTIST" + newline, and if the -h is not used as an option, then no header or new line would exist, but the rest of the script will run. If the user enters a different option such as -a, an invalid option message is displayed. My file "albums" is above, but here is the entire script and also the output with the messages. Note when i run the script without the -h it runs great, minus the header. When run it with -h, i have problems. Thanks again.

script (highest)
Code:
while getopts ":h" opt; do
  case $opt in
    h)
      print -n "ALBUMS ARTIST\n" >&2
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      ;;
  esac
done

filename=$1
filename=${filename:?"Filename Missing, include the filename after the \"highest\" script as an arguement."}
howmany=$2
sort -nr "$filename" | head -${howmany:=10}

output
Code:
$ highest albums 9
22 Tom Petty
20 Led Zeppelin
18 Stone Temple Pilots
17 Rolling Stones
16 Aerosmith
12 Black Crowes
10 Nirvana
8 Van Halen
5 ACDC
$ 
$ 
$ 
$ 
$ highest -h albums 9
ALBUMS ARTIST
sort: options '-hn' are incompatible
head: invalid option -- 'a'
Try 'head --help' for more information.
$

# 7  
Old 10-16-2013
First: you output the header line to <stderr> and the rest to <stdout>. This is possible, but <stderr>, as the name suggests, is for error messages and even if it does what you expect it to do you should reconsider.

Second: you haven't specified a certain shell to use (which you should indeed do), but your usage of "print" suggests you using a Kornshell. You do not need I/O-redirection in this case, Kornshells "print"-statement knows the parameter "-u<descriptor>", so that:

Code:
print -u2 "text to print"

will do the same as

Code:
print "text to print" >&2

Further, you do not need the "\n" at the end, print automatically adds a newline if you skip the "-n" option, which suppresses exactly that. Lastly, you should routinely use the "-" as the last option to make sure the string you want to print doesn't end up as being interpreted as parameter:

Code:
print -u2 - "text to print"

will work even if "text to print" would be replaced by text containing legal options to print, which would otherwise break your code. Here is an example:

Code:
text="-u2"
print "$text"         # will print nothing, because "$text" expands to an option
print - "$text"       # will print "-u2" as expected

Finally, I'd like to quote your first post:

Quote:
From the book:
The expression
${header:+"Albums Artist\n")
yields null if the variable header is null or "Albums Artist\n" is not null.
we can put the line:
print -n ${header:+"Albums Artist\n"}

My problem is i do not know how to make $header relate to the -h option.
Now that you know how to relate the "header" variable with the "-h" option you should not just copy what you found on the net, but put that mechanism to use for your own goals. Define a variable "header" and either put "-h" in there or not, depending on the "-h"-option being invoked or not. This should not be too hard, given that you now know how to use "getopts". Then use what is mentioned in your book to get what you want.

Here is a tip: you can look at the code while it executes and see what the shell really sees by using the "set -xv" command. Swithc that on with "set -xv" and off with "set +xv", like this:

Code:
#! /bin/ksh

# this part will be executed normally:

typeset variable="value"
typeset othervar="othervalue"

#watch execution from here:
set -xv

print - "variable: $variable     value of othervar: $othervar"

#switch it off again:
set +xv

print - "variable: $variable     value of othervar: $othervar"

exit 0

Save this to "myscript.ksh", slap on the excution bit and try it with:

Code:
./myscript.ksh 2>&1 | more

Tracing messages arrive at <stderr> and are first redirected to <stdout> ("2>&1"), then output is paginated by "more", which is not necessary in case of the short sample. For longer script parts, though, it is.

As "set +/- xv" only switches on and off tracing you can add it to interesting parts of scripts, watch what they do and move these commands around to inspect other parts. I do that regularly in my own scripts as part of my debugging routine.

I hope this helps.
bakunin
 
Login or Register to Ask a Question

Previous Thread | Next Thread

9 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

awk to retain header lines in output

The awk below executes and produces the current output, which is correct, except I can not seem to include the header lines # and ## in the output as well. I tried adding !/^#/ thinking that it would skip the lines with # and output them but the entire file prints as is. Thank you :). file ... (8 Replies)
Discussion started by: cmccabe
8 Replies

2. UNIX for Beginners Questions & Answers

Does anyone have a trick to run sdiff to display the filenames as a header?

Hi, Does anyone know if there is anyway to run sdiff such that it shows the name of the files as it display the results of the differences? That is, I want it to show the filenames on each column and then display the differences I can't find any option that allows this. Maybe someone has a... (2 Replies)
Discussion started by: newbie_01
2 Replies

3. UNIX for Advanced & Expert Users

Graphical Display Of Script Execution & Output

Hello All i have a KSH script which basically takes attribute name as input argument and searches whole Netezza appliance and prints information of where that column is used (Table/Views) etc. Problem with this approach business users have to raise SUDO access request, Install Putty, run through... (1 Reply)
Discussion started by: Ariean
1 Replies

4. Shell Programming and Scripting

How to display the header of a matched row in a file?

Hi, So I am trying to print the first row(header) first column alongwith the matched value. But I am not sure how do I print the same, by matching a pattern located in the file eg File contents Name Place Jim NY Jill NJ Cathy CA Sam TX Daniel FL And what I want is... (2 Replies)
Discussion started by: sidnow
2 Replies

5. Shell Programming and Scripting

Manipulate all rows except header, but header should be output as well

Hello There... I have a sample input file .. number:department:amount 125:Market:125.23 126:Hardware store:434.95 127:Video store:7.45 128:Book store:14.32 129:Gasolline:16.10 I will be doing some manipulations on all the records except the header, but the header should always be... (2 Replies)
Discussion started by: juzz4fun
2 Replies

6. Shell Programming and Scripting

Redirect an output from a script to a file and display it at a console simultaneously

Hi, I'd like to redirect the STDOUT output from my script to a file and simultaneously display it at a console. I've tried this command: myscript.sh | tail -f However, it doesn't end after the script finishes running I've also tried this: myscript.sh | tee ~/results.txt But it writes... (3 Replies)
Discussion started by: wenclu
3 Replies

7. Shell Programming and Scripting

Help with ksh script to display output with specific contents

This is Input - starts with Storage Group Name and ends with Shareable and the loop continues all I need is Storage group name and Alu numbers in the below output format requested. Storage Group Name: abcd Storage Group UID: 00:00:000:00:0:0:0 HBA/SP Pairs: HBA UID ... (6 Replies)
Discussion started by: maddysa
6 Replies

8. Shell Programming and Scripting

Need SQL output without the header.

Hi, In a script i am trying to run a SQL by connecting Sybase DB. While executing the script I am getting the output with the header. means: Employee_Name--------------------------- Anup Das I need the Output: Anup Das Kindly advice. (2 Replies)
Discussion started by: anupdas
2 Replies

9. Shell Programming and Scripting

getting the column header in the output !

i have a script that access the database and then returns some row. but in the command prompt it it not showing the column header. how to get that ? below the script: ------------------------------------------------------------------------ #!/bin/ksh .... (4 Replies)
Discussion started by: ali560045
4 Replies
Login or Register to Ask a Question