开发者

Creating a structure (datastructure) in shell script

开发者 https://www.devze.com 2023-04-05 06:32 出处:网络
I\'m really beginner in this field... My question is: how can I create a structure in shell script (or bash, I\'m not sure about the difference)

I'm really beginner in this field...

My question is: how can I create a structure in shell script (or bash, I'm not sure about the difference)

In C for example we can simply:

struct name
{
    __u8 x;
    __u8 y;
    signed short z;
    float t;
    float u;
};

Is it possible to create something similar to this in shell?

Why?

I need to copy some values to a /proc file..but I need to be sure about they are 12 bytes, and the ord开发者_运维问答er of them, because I want to assign them to the previous structure which is inside a linux kernel module

Thank you for any useful answer or hint


May I suggest a better tool for the job, Python? It's installed on most Linux systems, and you can write scripts with it, just put the appropriate shebang at the top:

#! /usr/bin/python

Or,

#! /usr/bin/env python

Then use struct module to pack values into binary representation.

#! /usr/bin/env python
import sys, struct
# Convert first 5 arguments
args = [f(arg) for f,arg in zip([int,int,int,float,float], sys.argv[1:])]
sys.stdout.write(struct.pack('BBhff',*args))

Which is equivalent to,

#! /usr/bin/env python
import sys, struct
x = int(sys.argv[1])
y = int(sys.argv[2])
z = int(sys.argv[3])
t = float(sys.argv[4])
u = float(sys.argv[5])
sys.stdout.write(struct.pack('BBhff',x,y,z,t,u))

And can be invoked as:

./script.py 1 2 3 4.0 5.0 > /proc/somefile...

EDIT: Or read from another file:

./script.py `cat args-file` > /proc/somefile...


You can use echo -en to dump out raw bytes with bash, for example echo -en "\000\001" will print out two bytes: 0x00 and 0x01. So you just need to know the specific bytes, encode them as octal values in your shell script, and then echo -en them to your proc file. I don't think you'll have much luck trying to convert a bash variable to a four byte float though; if you need to compute the values for your struct then bash isn't your best choice. I'd bet that someone around here could come up with a way to do it but that doesn't mean that it is the right thing to do.

Do you have Perl, Ruby, Python, PHP available? They all have a pack function for cramming native numbers into byte streams that will match the layout of a C struct. With any of those you could do some calculations, pack the values into your 12 byte format, and then dump them to your proc file.

Another option would be to write a small C program: include the appropriate header to get the module's struct, fill it in, and fwrite it to your proc file. This option would be my first choice as the header should take care of getting the padding and whatnot right.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号