Issue
I am writing a piece of code that has several outputs. The part where I output stuff has two functions, the first of which outputs some indented message. I would like the second function to print something starting from the indentation level of the previous output. So the second function should be aware of the indentation level of the first. How do I achieve this?
outputfunction1
outputfunction2
as opposed to
outputfunction1
outputfunction2
Thanks everyone
Solution
Here a fun (but terrible) idea.
#!/bin/sh
function1() { printf '\t\toutputfunction1\n'; }
function2() { echo bar; }
indent (){
indent=$(printf '%s' "$(for ((i=$1; $i>0; i--)); do printf '\t'; done)")
shift
$@ | sed "s/^/$indent/"
}
get_indent() {
# Call a function and return the indentation of the last line.
$@ | awk '1; END{ exit( match($0, "[^\t]") -1 )}'
}
get_indent function1
indent $? function2
Note that this relies on "indent" being defined as number of hard tabs. I'll leave it as an exercise for the reader to do this for arbitrary whitespace.
Answered By - William Pursell Answer Checked By - Mildred Charles (WPSolving Admin)