Sponsored Content
Top Forums Shell Programming and Scripting [bash] wanted: function with a clean way for multiple return values Post 302977109 by stomp on Tuesday 12th of July 2016 05:01:29 PM
Old 07-12-2016
[bash] wanted: function with a clean way for multiple return values

Hi,

I have a small part of a project which is done as a bash script. bash was selected as an portability issue that works out of the box. In this script I have an exec shell-function, a wrapper around arbitrary commands. I want to have STDOUT, as an addon STDERR and the EXIT-CODE of a specified command.

I'd like to have a clean wrapper, but my solution at the moment is ugly and does not produce clean code at the calling side. Maybe you have some hints to improve it.

In saying "clean" I'm thinking of side effect free programming, i. e. don't get into a mess with global variables and encapsulate all within the _exec function and just have that function to be called. (In the current situation, I have to use an additional line for every extra parameter I'm getting from _exec in the calling function.) I'd like to avoid eval("eval" should better be named "evil") too Smilie.

That's what I have so far:

Code:
function _dbg {
      # verbose logging here
}

function _fatal {
      # fatal error handling here
}

function _exec {
        local CMD=$1
        local OUT="$( $CMD 2>&1 ;echo "||$?" )"
        local EXIT_CODE="${OUT##*||}"

        # if no output is there at all [[:space:]]* does
        # not match. So do one with space and one without

        OUT="${OUT%[[:space:]]*||[0-9]*}"
        OUT="${OUT%||[0-9]*}"
        OUT="${OUT:-<EMPTY>}"

        if [ "$EXIT_CODE" != "0" ]; then
                _fatal $ESHELLERR "$EXIT_CODE" "$OUT" "$CMD"
        else
                _dbg "SHELL EXEC successful CMD: $CMD EXIT_CODE: $EXIT_CODE OUT: $OUT"
        fi
        echo "$EXIT_CODE||$OUT"
}

function _delete_compatible {

        local DIR="$1"
        local OUT="$(_exec "rm -rf $DIR")"
        local EXIT_CODE="${OUT%||*}"
        OUT="${OUT#*||}"
        if [ "$EXIT_CODE" == "0" ]; then
                _dbg "compatible delete successful"
                _success
        else
                echo "$OUT"
        fi
}

Not sure if this one will help me:
Returning Values from Bash Functions | Linux Journal

Last edited by stomp; 07-12-2016 at 06:21 PM..
 

10 More Discussions You Might Find Interesting

1. Programming

I need idas how to clean up this function.

OpenBSD complains when it sees this function in my program /*This function takes the string "test\n" and returns the string "test\n\test\ntest\n" ENTROPY = 1024 */ void *build_string(int count, char **strarr) { int k; char *new;; size_t max; if(count == 0) { ... (2 Replies)
Discussion started by: frequency8
2 Replies

2. Programming

returning multiple values from a function in C

hi how can I return multiple values from a C function. I tried the following: #include <stdio.h> void foo(int id, char *first_name, char *last_name) { /* this is just an example to illustrate my problem... real code makes use of the "id" parameter. */ first_name = (char... (8 Replies)
Discussion started by: Andrewkl
8 Replies

3. Shell Programming and Scripting

Can $? return multiple values?

Hi, I have a script which does something like the below: execute_some_script.sh $arg1 $arg2 `exec-some-cmd` if then; do something else do something else fi However, during some cases, there is an error saying: line xxx: [: too many arguments at the line number which has... (5 Replies)
Discussion started by: laloo
5 Replies

4. Shell Programming and Scripting

BASH: extracting values from multiple lines after a match

Hi there, I have the following output, # raidctl -l RAID Volume RAID RAID Disk Volume Type Status Disk Status ------------------------------------------------------ c0t1d0 IM OK c0t1d0 OK ... (4 Replies)
Discussion started by: rethink
4 Replies

5. Shell Programming and Scripting

Need Multiple Return Values

Hi, I need to retrun multiple values function errorFileCreation { echo "Before" return -1 "Siva"; echo "Aftyer" } echo ${?} - This can be used to getting first value. how can i get second one. Advance Thanks... Shiv (3 Replies)
Discussion started by: rsivasan
3 Replies

6. Programming

Passing multiple values from a function in C

I know multiple values can be returned from a function in C like this: char **read_file ( char * , unsigned long int * );//this is the function prototypeunsigned long int number_of_words = 0;//variable defined in main() and initialized to 0words_from_dictionary = read_file ( "dictionary.dit" ,... (2 Replies)
Discussion started by: shoaibjameel123
2 Replies

7. Programming

Problem with implementing the times() function in C (struct tms times return zero/negative values)

Hello, i'm trying to implement the times() function and i'm programming in C. I'm using the "struct tms" structure which consists of the fields: The tms_utime structure member is the CPU time charged for the execution of user instructions of the calling process. The tms_stime structure... (1 Reply)
Discussion started by: g_p
1 Replies

8. Shell Programming and Scripting

Bash - multiple line carriage return

Hello! I have one strange question - let's say I have a long, multiple-line string displayed on the terminal using echo, and I would like to make a carriage return to the beginning of this string, no to the beginning of the last line - is something like that possible? I would like to be able to... (1 Reply)
Discussion started by: xqwzts
1 Replies

9. Shell Programming and Scripting

Return multiple values using for loop in perl

I am using a for loop to copy files from say DIR1 and DIR2 to DIR3.I have to check whether files are copied from DIR1 and DIR2 and print the respective message. @path=("$DIR1","$DIR2"); foreach (@path) { $rc=system("cp $_/*xml $DIR3"); if ($rc == 0) { print "Files were copied... (1 Reply)
Discussion started by: liyakathali
1 Replies

10. Shell Programming and Scripting

Returning and capturing multiple return values from a function

Hi I am pretty confused in returning and capturing multiple values i have defined a function which should return values "total, difference" i have used as #!/usr/bin/ksh calc() { total=$1+$2 echo "$total" diff=$2-$1 echo "$diff" } I have invoked this function as calc 5 8 Now i... (2 Replies)
Discussion started by: Priya Amaresh
2 Replies
TEXI2DVI(1)							   User Commands						       TEXI2DVI(1)

NAME
texi2dvi - convert Texinfo documents to PDF SYNOPSIS
texi2dvi [OPTION]... FILE... DESCRIPTION
Run each Texinfo or (La)TeX FILE through TeX in turn until all cross-references are resolved, building all indices. The directory contain- ing each FILE is searched for included files. The suffix of FILE is used to determine its language ((La)TeX or Texinfo). To process (e)plain TeX files, set the environment variable LATEX=tex. In order to make texi2dvi a drop-in replacement of TeX/LaTeX in AUC-TeX, the FILE may also be composed of the following simple TeX com- mands. `input{FILE}' the actual file to compile ` onstopmode' same as --batch Makeinfo is used to perform Texinfo macro expansion before running TeX when needed. General options: -b, --batch no interaction -D, --debug turn on shell debugging (set -x) -h, --help display this help and exit successfully -o, --output=OFILE leave output in OFILE (implies --clean); only one input FILE may be specified in this case -q, --quiet no output unless errors (implies --batch) -s, --silent same as --quiet -v, --version display version information and exit successfully -V, --verbose report on what is done TeX tuning: -@ use @input instead of input for preloaded Texinfo --dvi output a DVI file [default] --dvipdf output a PDF file via DVI (using dvipdf) -e, -E, --expand force macro expansion using makeinfo -I DIR search DIR for Texinfo files -l, --language=LANG specify LANG for FILE, either latex or texinfo --no-line-error do not pass --file-line-error to TeX -p, --pdf use pdftex or pdflatex for processing -r, --recode call recode before TeX to translate input --recode-from=ENC recode from ENC to the @documentencoding --src-specials pass --src-specials to TeX -t, --command=CMD insert CMD in copy of input file or --texinfo=CMD multiple values accumulate --translate-file=FILE use given charset translation file for TeX Build modes: --build=MODE specify the treatment of auxiliary files [local] --tidy same as --build=tidy -c, --clean same as --build=clean --build-dir=DIR specify where the tidy compilation is performed; implies --tidy; defaults to TEXI2DVI_BUILD_DIRECTORY [.] --mostly-clean remove the auxiliary files and directories but not the output The MODE specifies where the TeX compilation takes place, and, as a consequence, how auxiliary files are treated. The build mode can also be set using the environment variable TEXI2DVI_BUILD_MODE. Valid MODEs are: `local' compile in the current directory, leaving all the auxiliary files around. This is the traditional TeX use. `tidy' compile in a local *.t2d directory, where the auxiliary files are left. Output files are copied back to the original file. `clean' same as `tidy', but remove the auxiliary directory afterwards. Every compilation therefore requires the full cycle. Using the `tidy' mode brings several advantages: - the current directory is not cluttered with plethora of temporary files. - clutter can be even reduced using --build-dir=dir: all the *.t2d directories are stored there. - clutter can be reduced to zero using, e.g., --build-dir=/tmp/$USER.t2d or --build-dir=$HOME/.t2d. - the output file is updated after every succesful TeX run, for sake of concurrent visualization of the output. In a `local' build the viewer stops during the whole TeX run. - if the compilation fails, the previous state of the output file is preserved. - PDF and DVI compilation are kept in separate subdirectories preventing any possibility of auxiliary file incompatibility. On the other hand, because `tidy' compilation takes place in another directory, occasionally TeX won't be able to find some files (e.g., when using graphicspath): in that case use -I to specify the additional directories to consider. The values of the BIBTEX, LATEX (or PDFLATEX), MAKEINDEX, MAKEINFO, TEX (or PDFTEX), TEXINDEX, and THUMBPDF environment variables are used to run those commands, if they are set. Any CMD strings are added after @setfilename for Texinfo input, in the first line for LaTeX input. REPORTING BUGS
Email bug reports to <bug-texinfo@gnu.org>, general questions and discussion to <help-texinfo@gnu.org>. Texinfo home page: http://www.gnu.org/software/texinfo/ COPYRIGHT
Copyright (C) 2008 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO
The full documentation for texi2dvi is maintained as a Texinfo manual. If the info and texi2dvi programs are properly installed at your site, the command info texi2dvi should give you access to the complete manual. texi2dvi 1.135 July 2010 TEXI2DVI(1)
All times are GMT -4. The time now is 09:48 AM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy